常用查询方法

常用查询操作

  1. ###获取所有记录:
  2. rs = User.objects.al1()
  3. ###获取第一条数据:
  4. rs = User.objects.first()
  5. ###获取最后一条数据:
  6. rs =user .objects.last()
  7. ###根据参数提供的条件获取过滤后的记录:
  8. rs = User.objects.filter( name=" xiaoming" )
  9. 注意:filter(**kwargs)方法:根据参数提供的提取条件,获取一个过滤后的QuerySet
  10. ###排除name等于xiaoming的记录:
  11. rs = User.objects.exclude ( name= "xiaoming " )
  12. ###获取一个记录对象:
  13. rs = User.objects-get( name= " xiaoming")
  14. ###注意:get返回的对象具有唯一性质,如果符合条件的对象有多个,则get报错!
  15. ###对结果排序order_by :
  16. rs-user .objects.order_by ("age" )
  17. ###多项排序:
  18. rs =User.objects.order_by( " age" ,'id " )
  19. ###逆向排序:
  20. rs =User .objects.order_by (" -age")
  21. ###将返回来的Queryset中的Mode1转换为字典
  22. rs =User .objects.all().values()
  23. ###获取当前查询到的娄数据的总娄女:
  24. rs =User .objects.count()

常用查询条件

  1. ###exact相当于等于号:
  2. rs = User.objects.filter( name__exact= "xiaoming' )
  3. ###iexact:跟exact,只是忽略大小写的匹配。
  4. ###contains包含:
  5. rs = User.objects.filter( name__contains="xiao)
  6. ##icontains跟contains,唯—不同是忽略大小写。
  7. ###startwith 以什么开始:
  8. rs = User.objects.filter( name__startswith= 'xiao")
  9. ###istartswith :同startswith,忽略大小写。
  10. ###endswith :司startswith,以什么结尾。
  11. ###iendswith :同istartswith,以什么结尾,忽略大小写。
  12. ###in成员所属:
  13. rs - User.objects.filter(age__in=[ 18,19,20])
  14. gt大于:
  15. rs = User.objects.filter(age__gt=2e)
  16. gte大于等于:
  17. rs - User.objects.filter(age__gte=20)
  18. lt小于:
  19. rs = User.objects.filter(age__lt=2e)
  20. lte小于等于:
  21. rs - User.objects.filter(age__lte=20)
  22. range区间:
  23. rs - user.objects.filter(age__range=(18,20))
  24. isnul1 判断是否为空:|
  25. rs = User.objects.filter(city__isnull=True)

常用字段类型的映射关系

  1. ### int =============> lntegetField
  2. ### varchar==========> CharField
  3. ### longtext=========> TextField
  4. ### date ============> DateField
  5. ### DateTimeField ===> datetime

字段源码阅读

  1. BooleanField

  1. class BooleanField(Field):
  2. empty_strings_allowed = False
  3. default_error_messages = {
  4. 'invalid': _("'%(value)s' value must be either True or False."),
  5. 'invalid_nullable': _("'%(value)s' value must be either True, False, or None."),
  6. }
  7. description = _("Boolean (Either True or False)")
  8. def get_internal_type(self):
  9. return "BooleanField"
  10. def to_python(self, value):
  11. if self.null and value in self.empty_values:
  12. return None
  13. if value in (True, False):
  14. # if value is 1 or 0 than it's equal to True or False, but we want
  15. # to return a true bool for semantic reasons. # semantic---语义的
  16. return bool(value)
  17. # 兼容性:容许三种输入值
  18. if value in ('t', 'True', '1'):
  19. return True
  20. if value in ('f', 'False', '0'):
  21. return False
  22. raise exceptions.ValidationError(
  23. self.error_messages['invalid_nullable' if self.null else 'invalid'],
  24. code='invalid',
  25. params={'value': value},
  26. )
  27. def get_prep_value(self, value):
  28. value = super().get_prep_value(value)
  29. if value is None:
  30. return None
  31. return self.to_python(value)
  1. CharField

  1. class CharField(Field):
  2. description = _("String (up to %(max_length)s)")
  3. def __init__(self, *args, **kwargs):
  4. super().__init__(*args, **kwargs)
  5. self.validators.append(validators.MaxLengthValidator(self.max_length))
  6. def check(self, **kwargs):
  7. return [
  8. *super().check(**kwargs),
  9. *self._check_max_length_attribute(**kwargs),
  10. ]
  11. def _check_max_length_attribute(self, **kwargs):
  12. if self.max_length is None:
  13. return [
  14. checks.Error(
  15. "CharFields must define a 'max_length' attribute.",
  16. obj=self,
  17. id='fields.E120',
  18. )
  19. ]
  20. elif (not isinstance(self.max_length, int) or isinstance(self.max_length, bool) or
  21. self.max_length <= 0):
  22. return [
  23. checks.Error(
  24. "'max_length' must be a positive integer.",
  25. obj=self,
  26. id='fields.E121',
  27. )
  28. ]
  29. else:
  30. return []
  31. def cast_db_type(self, connection):
  32. if self.max_length is None:
  33. return connection.ops.cast_char_field_without_max_length
  34. return super().cast_db_type(connection)
  35. def get_internal_type(self):
  36. return "CharField"
  37. def to_python(self, value):
  38. if isinstance(value, str) or value is None:
  39. return value
  40. return str(value)
  41. def get_prep_value(self, value):
  42. value = super().get_prep_value(value)
  43. return self.to_python(value)
  44. def formfield(self, **kwargs):
  45. # Passing max_length to forms.CharField means that the value's length
  46. # will be validated twice. This is considered acceptable since we want
  47. # the value in the form field (to pass into widget for example).
  48. defaults = {'max_length': self.max_length}
  49. # TODO: Handle multiple backends with different feature flags.
  50. if self.null and not connection.features.interprets_empty_strings_as_nulls:
  51. defaults['empty_value'] = None
  52. defaults.update(kwargs)
  53. return super().formfield(**defaults)

常用的模型字段类型

常用字段类型

  1. 1.IntegerField :整型,映射到数据库中的int类型。
  2. 2.CharField:字符类型,映射到数据库中的varchar类型,通过max_length指定最大长度。
  3. 3.TextField:文本类型,映射到数据库中的text类型。
  4. 4.BooleanField:布尔类型,映射到数据库中的tinyint类型,在使用的时候,传递True/False进去。如果要可以为空,则用NullBooleanField
  5. 5.DateField:日期类型,没有时间。映射到数据库中是date类型,
  6. 在使用的时候,可以设置DateField.auto_now每次保存对象时,自动设置该字段为当前时间。设置DateField.auto_now_add当对象第一次被创建时自动设置当前时间。
  7. 6.DateTimeField:日期时间类型。映射到数据库中的是datetime类型,在使用的时候,传递datetime.datetime()进去。

Field常用参数

  1. primary_key:指定是否为主键。
  2. unique:指定是否唯一。
  3. null:指定是否为空,默认为False
  4. blank:等于Trueform表单验证时可以为空,默认为False
  5. default:设置默认值。
  6. DateField.auto now:每次修改都会将当前时间更新进去,只有调用,QuerySet.update方法将不会调用。这个参数只是DateDateTime以及TimModel.save()方法才会调用e类才有的。
  7. DateField.auto _now add: 第一次添加进去,都会将当前时间设置进去。以后修改,不会修改这个值

Field的常用操作和表关系的实现

Field 源码

  1. @total_ordering
  2. class Field(RegisterLookupMixin):
  3. """Base class for all field types"""
  4. # Designates whether empty strings fundamentally are allowed at the
  5. # database level.
  6. empty_strings_allowed = True
  7. empty_values = list(validators.EMPTY_VALUES)
  8. # These track each time a Field instance is created. Used to retain order.
  9. # The auto_creation_counter is used for fields that Django implicitly
  10. # creates, creation_counter is used for all user-specified fields.
  11. creation_counter = 0
  12. auto_creation_counter = -1
  13. default_validators = [] # Default set of validators
  14. default_error_messages = {
  15. 'invalid_choice': _('Value %(value)r is not a valid choice.'),
  16. 'null': _('This field cannot be null.'),
  17. 'blank': _('This field cannot be blank.'),
  18. 'unique': _('%(model_name)s with this %(field_label)s '
  19. 'already exists.'),
  20. # Translators: The 'lookup_type' is one of 'date', 'year' or 'month'.
  21. # Eg: "Title must be unique for pub_date year"
  22. 'unique_for_date': _("%(field_label)s must be unique for "
  23. "%(date_field_label)s %(lookup_type)s."),
  24. }
  25. system_check_deprecated_details = None
  26. system_check_removed_details = None
  27. # Field flags
  28. hidden = False
  29. many_to_many = None
  30. many_to_one = None
  31. one_to_many = None
  32. one_to_one = None
  33. related_model = None
  34. # Generic field type description, usually overridden by subclasses
  35. def _description(self):
  36. return _('Field of type: %(field_type)s') % {
  37. 'field_type': self.__class__.__name__
  38. }
  39. description = property(_description)
  40. def __init__(self, verbose_name=None, name=None, primary_key=False,
  41. max_length=None, unique=False, blank=False, null=False,
  42. db_index=False, rel=None, default=NOT_PROVIDED, editable=True,
  43. serialize=True, unique_for_date=None, unique_for_month=None,
  44. unique_for_year=None, choices=None, help_text='', db_column=None,
  45. db_tablespace=None, auto_created=False, validators=(),
  46. error_messages=None):
  47. self.name = name
  48. self.verbose_name = verbose_name # May be set by set_attributes_from_name
  49. self._verbose_name = verbose_name # Store original for deconstruction
  50. self.primary_key = primary_key
  51. self.max_length, self._unique = max_length, unique
  52. self.blank, self.null = blank, null
  53. self.remote_field = rel
  54. self.is_relation = self.remote_field is not None
  55. self.default = default
  56. self.editable = editable
  57. self.serialize = serialize
  58. self.unique_for_date = unique_for_date
  59. self.unique_for_month = unique_for_month
  60. self.unique_for_year = unique_for_year
  61. if isinstance(choices, collections.abc.Iterator):
  62. choices = list(choices)
  63. self.choices = choices or []
  64. self.help_text = help_text
  65. self.db_index = db_index
  66. self.db_column = db_column
  67. self._db_tablespace = db_tablespace
  68. self.auto_created = auto_created
  69. # Adjust the appropriate creation counter, and save our local copy.
  70. if auto_created:
  71. self.creation_counter = Field.auto_creation_counter
  72. Field.auto_creation_counter -= 1
  73. else:
  74. self.creation_counter = Field.creation_counter
  75. Field.creation_counter += 1
  76. self._validators = list(validators) # Store for deconstruction later
  77. messages = {}
  78. for c in reversed(self.__class__.__mro__):
  79. messages.update(getattr(c, 'default_error_messages', {}))
  80. messages.update(error_messages or {})
  81. self._error_messages = error_messages # Store for deconstruction later
  82. self.error_messages = messages
  83. def __str__(self):
  84. """
  85. Return "app_label.model_label.field_name" for fields attached to
  86. models.
  87. """
  88. if not hasattr(self, 'model'):
  89. return super().__str__()
  90. model = self.model
  91. app = model._meta.app_label
  92. return '%s.%s.%s' % (app, model._meta.object_name, self.name)
  93. def __repr__(self):
  94. """Display the module, class, and name of the field."""
  95. path = '%s.%s' % (self.__class__.__module__, self.__class__.__qualname__)
  96. name = getattr(self, 'name', None)
  97. if name is not None:
  98. return '<%s: %s>' % (path, name)
  99. return '<%s>' % path
  100. def check(self, **kwargs):
  101. return [
  102. *self._check_field_name(),
  103. *self._check_choices(),
  104. *self._check_db_index(),
  105. *self._check_null_allowed_for_primary_keys(),
  106. *self._check_backend_specific_checks(**kwargs),
  107. *self._check_validators(),
  108. *self._check_deprecation_details(),
  109. ]
  110. def _check_field_name(self):
  111. """
  112. Check if field name is valid, i.e. 1) does not end with an
  113. underscore, 2) does not contain "__" and 3) is not "pk".
  114. """
  115. if self.name.endswith('_'):
  116. return [
  117. checks.Error(
  118. 'Field names must not end with an underscore.',
  119. obj=self,
  120. id='fields.E001',
  121. )
  122. ]
  123. elif LOOKUP_SEP in self.name:
  124. return [
  125. checks.Error(
  126. 'Field names must not contain "%s".' % (LOOKUP_SEP,),
  127. obj=self,
  128. id='fields.E002',
  129. )
  130. ]
  131. elif self.name == 'pk':
  132. return [
  133. checks.Error(
  134. "'pk' is a reserved word that cannot be used as a field name.",
  135. obj=self,
  136. id='fields.E003',
  137. )
  138. ]
  139. else:
  140. return []
  141. def _check_choices(self):
  142. if not self.choices:
  143. return []
  144. def is_value(value, accept_promise=True):
  145. return isinstance(value, (str, Promise) if accept_promise else str) or not is_iterable(value)
  146. if is_value(self.choices, accept_promise=False):
  147. return [
  148. checks.Error(
  149. "'choices' must be an iterable (e.g., a list or tuple).",
  150. obj=self,
  151. id='fields.E004',
  152. )
  153. ]
  154. # Expect [group_name, [value, display]]
  155. for choices_group in self.choices:
  156. try:
  157. group_name, group_choices = choices_group
  158. except ValueError:
  159. # Containing non-pairs
  160. break
  161. try:
  162. if not all(
  163. is_value(value) and is_value(human_name)
  164. for value, human_name in group_choices
  165. ):
  166. break
  167. except (TypeError, ValueError):
  168. # No groups, choices in the form [value, display]
  169. value, human_name = group_name, group_choices
  170. if not is_value(value) or not is_value(human_name):
  171. break
  172. # Special case: choices=['ab']
  173. if isinstance(choices_group, str):
  174. break
  175. else:
  176. return []
  177. return [
  178. checks.Error(
  179. "'choices' must be an iterable containing "
  180. "(actual value, human readable name) tuples.",
  181. obj=self,
  182. id='fields.E005',
  183. )
  184. ]
  185. def _check_db_index(self):
  186. if self.db_index not in (None, True, False):
  187. return [
  188. checks.Error(
  189. "'db_index' must be None, True or False.",
  190. obj=self,
  191. id='fields.E006',
  192. )
  193. ]
  194. else:
  195. return []
  196. def _check_null_allowed_for_primary_keys(self):
  197. if (self.primary_key and self.null and
  198. not connection.features.interprets_empty_strings_as_nulls):
  199. # We cannot reliably check this for backends like Oracle which
  200. # consider NULL and '' to be equal (and thus set up
  201. # character-based fields a little differently).
  202. return [
  203. checks.Error(
  204. 'Primary keys must not have null=True.',
  205. hint=('Set null=False on the field, or '
  206. 'remove primary_key=True argument.'),
  207. obj=self,
  208. id='fields.E007',
  209. )
  210. ]
  211. else:
  212. return []
  213. def _check_backend_specific_checks(self, **kwargs):
  214. app_label = self.model._meta.app_label
  215. for db in connections:
  216. if router.allow_migrate(db, app_label, model_name=self.model._meta.model_name):
  217. return connections[db].validation.check_field(self, **kwargs)
  218. return []
  219. def _check_validators(self):
  220. errors = []
  221. for i, validator in enumerate(self.validators):
  222. if not callable(validator):
  223. errors.append(
  224. checks.Error(
  225. "All 'validators' must be callable.",
  226. hint=(
  227. "validators[{i}] ({repr}) isn't a function or "
  228. "instance of a validator class.".format(
  229. i=i, repr=repr(validator),
  230. )
  231. ),
  232. obj=self,
  233. id='fields.E008',
  234. )
  235. )
  236. return errors
  237. def _check_deprecation_details(self):
  238. if self.system_check_removed_details is not None:
  239. return [
  240. checks.Error(
  241. self.system_check_removed_details.get(
  242. 'msg',
  243. '%s has been removed except for support in historical '
  244. 'migrations.' % self.__class__.__name__
  245. ),
  246. hint=self.system_check_removed_details.get('hint'),
  247. obj=self,
  248. id=self.system_check_removed_details.get('id', 'fields.EXXX'),
  249. )
  250. ]
  251. elif self.system_check_deprecated_details is not None:
  252. return [
  253. checks.Warning(
  254. self.system_check_deprecated_details.get(
  255. 'msg',
  256. '%s has been deprecated.' % self.__class__.__name__
  257. ),
  258. hint=self.system_check_deprecated_details.get('hint'),
  259. obj=self,
  260. id=self.system_check_deprecated_details.get('id', 'fields.WXXX'),
  261. )
  262. ]
  263. return []
  264. def get_col(self, alias, output_field=None):
  265. if output_field is None:
  266. output_field = self
  267. if alias != self.model._meta.db_table or output_field != self:
  268. from django.db.models.expressions import Col
  269. return Col(alias, self, output_field)
  270. else:
  271. return self.cached_col
  272. @cached_property
  273. def cached_col(self):
  274. from django.db.models.expressions import Col
  275. return Col(self.model._meta.db_table, self)
  276. def select_format(self, compiler, sql, params):
  277. """
  278. Custom format for select clauses. For example, GIS columns need to be
  279. selected as AsText(table.col) on MySQL as the table.col data can't be
  280. used by Django.
  281. """
  282. return sql, params
  283. def deconstruct(self):
  284. """
  285. Return enough information to recreate the field as a 4-tuple:
  286. * The name of the field on the model, if contribute_to_class() has
  287. been run.
  288. * The import path of the field, including the class:e.g.
  289. django.db.models.IntegerField This should be the most portable
  290. version, so less specific may be better.
  291. * A list of positional arguments.
  292. * A dict of keyword arguments.
  293. Note that the positional or keyword arguments must contain values of
  294. the following types (including inner values of collection types):
  295. * None, bool, str, int, float, complex, set, frozenset, list, tuple,
  296. dict
  297. * UUID
  298. * datetime.datetime (naive), datetime.date
  299. * top-level classes, top-level functions - will be referenced by their
  300. full import path
  301. * Storage instances - these have their own deconstruct() method
  302. This is because the values here must be serialized into a text format
  303. (possibly new Python code, possibly JSON) and these are the only types
  304. with encoding handlers defined.
  305. There's no need to return the exact way the field was instantiated this
  306. time, just ensure that the resulting field is the same - prefer keyword
  307. arguments over positional ones, and omit parameters with their default
  308. values.
  309. """
  310. # Short-form way of fetching all the default parameters
  311. keywords = {}
  312. possibles = {
  313. "verbose_name": None,
  314. "primary_key": False,
  315. "max_length": None,
  316. "unique": False,
  317. "blank": False,
  318. "null": False,
  319. "db_index": False,
  320. "default": NOT_PROVIDED,
  321. "editable": True,
  322. "serialize": True,
  323. "unique_for_date": None,
  324. "unique_for_month": None,
  325. "unique_for_year": None,
  326. "choices": [],
  327. "help_text": '',
  328. "db_column": None,
  329. "db_tablespace": None,
  330. "auto_created": False,
  331. "validators": [],
  332. "error_messages": None,
  333. }
  334. attr_overrides = {
  335. "unique": "_unique",
  336. "error_messages": "_error_messages",
  337. "validators": "_validators",
  338. "verbose_name": "_verbose_name",
  339. "db_tablespace": "_db_tablespace",
  340. }
  341. equals_comparison = {"choices", "validators"}
  342. for name, default in possibles.items():
  343. value = getattr(self, attr_overrides.get(name, name))
  344. # Unroll anything iterable for choices into a concrete list
  345. if name == "choices" and isinstance(value, collections.abc.Iterable):
  346. value = list(value)
  347. # Do correct kind of comparison
  348. if name in equals_comparison:
  349. if value != default:
  350. keywords[name] = value
  351. else:
  352. if value is not default:
  353. keywords[name] = value
  354. # Work out path - we shorten it for known Django core fields
  355. path = "%s.%s" % (self.__class__.__module__, self.__class__.__qualname__)
  356. if path.startswith("django.db.models.fields.related"):
  357. path = path.replace("django.db.models.fields.related", "django.db.models")
  358. if path.startswith("django.db.models.fields.files"):
  359. path = path.replace("django.db.models.fields.files", "django.db.models")
  360. if path.startswith("django.db.models.fields.proxy"):
  361. path = path.replace("django.db.models.fields.proxy", "django.db.models")
  362. if path.startswith("django.db.models.fields"):
  363. path = path.replace("django.db.models.fields", "django.db.models")
  364. # Return basic info - other fields should override this.
  365. return (self.name, path, [], keywords)
  366. def clone(self):
  367. """
  368. Uses deconstruct() to clone a new copy of this Field.
  369. Will not preserve any class attachments/attribute names.
  370. """
  371. name, path, args, kwargs = self.deconstruct()
  372. return self.__class__(*args, **kwargs)
  373. def __eq__(self, other):
  374. # Needed for @total_ordering
  375. if isinstance(other, Field):
  376. return self.creation_counter == other.creation_counter
  377. return NotImplemented
  378. def __lt__(self, other):
  379. # This is needed because bisect does not take a comparison function.
  380. if isinstance(other, Field):
  381. return self.creation_counter < other.creation_counter
  382. return NotImplemented
  383. def __hash__(self):
  384. return hash(self.creation_counter)
  385. def __deepcopy__(self, memodict):
  386. # We don't have to deepcopy very much here, since most things are not
  387. # intended to be altered after initial creation.
  388. obj = copy.copy(self)
  389. if self.remote_field:
  390. obj.remote_field = copy.copy(self.remote_field)
  391. if hasattr(self.remote_field, 'field') and self.remote_field.field is self:
  392. obj.remote_field.field = obj
  393. memodict[id(self)] = obj
  394. return obj
  395. def __copy__(self):
  396. # We need to avoid hitting __reduce__, so define this
  397. # slightly weird copy construct.
  398. obj = Empty()
  399. obj.__class__ = self.__class__
  400. obj.__dict__ = self.__dict__.copy()
  401. return obj
  402. def __reduce__(self):
  403. """
  404. Pickling should return the model._meta.fields instance of the field,
  405. not a new copy of that field. So, use the app registry to load the
  406. model and then the field back.
  407. """
  408. if not hasattr(self, 'model'):
  409. # Fields are sometimes used without attaching them to models (for
  410. # example in aggregation). In this case give back a plain field
  411. # instance. The code below will create a new empty instance of
  412. # class self.__class__, then update its dict with self.__dict__
  413. # values - so, this is very close to normal pickle.
  414. state = self.__dict__.copy()
  415. # The _get_default cached_property can't be pickled due to lambda
  416. # usage.
  417. state.pop('_get_default', None)
  418. return _empty, (self.__class__,), state
  419. return _load_field, (self.model._meta.app_label, self.model._meta.object_name,
  420. self.name)
  421. def get_pk_value_on_save(self, instance):
  422. """
  423. Hook to generate new PK values on save. This method is called when
  424. saving instances with no primary key value set. If this method returns
  425. something else than None, then the returned value is used when saving
  426. the new instance.
  427. """
  428. if self.default:
  429. return self.get_default()
  430. return None
  431. def to_python(self, value):
  432. """
  433. Convert the input value into the expected Python data type, raising
  434. django.core.exceptions.ValidationError if the data can't be converted.
  435. Return the converted value. Subclasses should override this.
  436. """
  437. return value
  438. @cached_property
  439. def validators(self):
  440. """
  441. Some validators can't be created at field initialization time.
  442. This method provides a way to delay their creation until required.
  443. """
  444. return [*self.default_validators, *self._validators]
  445. def run_validators(self, value):
  446. if value in self.empty_values:
  447. return
  448. errors = []
  449. for v in self.validators:
  450. try:
  451. v(value)
  452. except exceptions.ValidationError as e:
  453. if hasattr(e, 'code') and e.code in self.error_messages:
  454. e.message = self.error_messages[e.code]
  455. errors.extend(e.error_list)
  456. if errors:
  457. raise exceptions.ValidationError(errors)
  458. def validate(self, value, model_instance):
  459. """
  460. Validate value and raise ValidationError if necessary. Subclasses
  461. should override this to provide validation logic.
  462. """
  463. if not self.editable:
  464. # Skip validation for non-editable fields.
  465. return
  466. if self.choices and value not in self.empty_values:
  467. for option_key, option_value in self.choices:
  468. if isinstance(option_value, (list, tuple)):
  469. # This is an optgroup, so look inside the group for
  470. # options.
  471. for optgroup_key, optgroup_value in option_value:
  472. if value == optgroup_key:
  473. return
  474. elif value == option_key:
  475. return
  476. raise exceptions.ValidationError(
  477. self.error_messages['invalid_choice'],
  478. code='invalid_choice',
  479. params={'value': value},
  480. )
  481. if value is None and not self.null:
  482. raise exceptions.ValidationError(self.error_messages['null'], code='null')
  483. if not self.blank and value in self.empty_values:
  484. raise exceptions.ValidationError(self.error_messages['blank'], code='blank')
  485. def clean(self, value, model_instance):
  486. """
  487. Convert the value's type and run validation. Validation errors
  488. from to_python() and validate() are propagated. Return the correct
  489. value if no error is raised.
  490. """
  491. value = self.to_python(value)
  492. self.validate(value, model_instance)
  493. self.run_validators(value)
  494. return value
  495. def db_type_parameters(self, connection):
  496. return DictWrapper(self.__dict__, connection.ops.quote_name, 'qn_')
  497. def db_check(self, connection):
  498. """
  499. Return the database column check constraint for this field, for the
  500. provided connection. Works the same way as db_type() for the case that
  501. get_internal_type() does not map to a preexisting model field.
  502. """
  503. data = self.db_type_parameters(connection)
  504. try:
  505. return connection.data_type_check_constraints[self.get_internal_type()] % data
  506. except KeyError:
  507. return None
  508. def db_type(self, connection):
  509. """
  510. Return the database column data type for this field, for the provided
  511. connection.
  512. """
  513. # The default implementation of this method looks at the
  514. # backend-specific data_types dictionary, looking up the field by its
  515. # "internal type".
  516. #
  517. # A Field class can implement the get_internal_type() method to specify
  518. # which *preexisting* Django Field class it's most similar to -- i.e.,
  519. # a custom field might be represented by a TEXT column type, which is
  520. # the same as the TextField Django field type, which means the custom
  521. # field's get_internal_type() returns 'TextField'.
  522. #
  523. # But the limitation of the get_internal_type() / data_types approach
  524. # is that it cannot handle database column types that aren't already
  525. # mapped to one of the built-in Django field types. In this case, you
  526. # can implement db_type() instead of get_internal_type() to specify
  527. # exactly which wacky database column type you want to use.
  528. data = self.db_type_parameters(connection)
  529. try:
  530. return connection.data_types[self.get_internal_type()] % data
  531. except KeyError:
  532. return None
  533. def rel_db_type(self, connection):
  534. """
  535. Return the data type that a related field pointing to this field should
  536. use. For example, this method is called by ForeignKey and OneToOneField
  537. to determine its data type.
  538. """
  539. return self.db_type(connection)
  540. def cast_db_type(self, connection):
  541. """Return the data type to use in the Cast() function."""
  542. db_type = connection.ops.cast_data_types.get(self.get_internal_type())
  543. if db_type:
  544. return db_type % self.db_type_parameters(connection)
  545. return self.db_type(connection)
  546. def db_parameters(self, connection):
  547. """
  548. Extension of db_type(), providing a range of different return values
  549. (type, checks). This will look at db_type(), allowing custom model
  550. fields to override it.
  551. """
  552. type_string = self.db_type(connection)
  553. check_string = self.db_check(connection)
  554. return {
  555. "type": type_string,
  556. "check": check_string,
  557. }
  558. def db_type_suffix(self, connection):
  559. return connection.data_types_suffix.get(self.get_internal_type())
  560. def get_db_converters(self, connection):
  561. if hasattr(self, 'from_db_value'):
  562. return [self.from_db_value]
  563. return []
  564. @property
  565. def unique(self):
  566. return self._unique or self.primary_key
  567. @property
  568. def db_tablespace(self):
  569. return self._db_tablespace or settings.DEFAULT_INDEX_TABLESPACE
  570. def set_attributes_from_name(self, name):
  571. self.name = self.name or name
  572. self.attname, self.column = self.get_attname_column()
  573. self.concrete = self.column is not None
  574. if self.verbose_name is None and self.name:
  575. self.verbose_name = self.name.replace('_', ' ')
  576. def contribute_to_class(self, cls, name, private_only=False):
  577. """
  578. Register the field with the model class it belongs to.
  579. If private_only is True, create a separate instance of this field
  580. for every subclass of cls, even if cls is not an abstract model.
  581. """
  582. self.set_attributes_from_name(name)
  583. self.model = cls
  584. if private_only:
  585. cls._meta.add_field(self, private=True)
  586. else:
  587. cls._meta.add_field(self)
  588. if self.column:
  589. # Don't override classmethods with the descriptor. This means that
  590. # if you have a classmethod and a field with the same name, then
  591. # such fields can't be deferred (we don't have a check for this).
  592. if not getattr(cls, self.attname, None):
  593. setattr(cls, self.attname, DeferredAttribute(self.attname))
  594. if self.choices:
  595. setattr(cls, 'get_%s_display' % self.name,
  596. partialmethod(cls._get_FIELD_display, field=self))
  597. def get_filter_kwargs_for_object(self, obj):
  598. """
  599. Return a dict that when passed as kwargs to self.model.filter(), would
  600. yield all instances having the same value for this field as obj has.
  601. """
  602. return {self.name: getattr(obj, self.attname)}
  603. def get_attname(self):
  604. return self.name
  605. def get_attname_column(self):
  606. attname = self.get_attname()
  607. column = self.db_column or attname
  608. return attname, column
  609. def get_internal_type(self):
  610. return self.__class__.__name__
  611. def pre_save(self, model_instance, add):
  612. """Return field's value just before saving."""
  613. return getattr(model_instance, self.attname)
  614. def get_prep_value(self, value):
  615. """Perform preliminary non-db specific value checks and conversions."""
  616. if isinstance(value, Promise):
  617. value = value._proxy____cast()
  618. return value
  619. def get_db_prep_value(self, value, connection, prepared=False):
  620. """
  621. Return field's value prepared for interacting with the database backend.
  622. Used by the default implementations of get_db_prep_save().
  623. """
  624. if not prepared:
  625. value = self.get_prep_value(value)
  626. return value
  627. def get_db_prep_save(self, value, connection):
  628. """Return field's value prepared for saving into a database."""
  629. return self.get_db_prep_value(value, connection=connection, prepared=False)
  630. def has_default(self):
  631. """Return a boolean of whether this field has a default value."""
  632. return self.default is not NOT_PROVIDED
  633. def get_default(self):
  634. """Return the default value for this field."""
  635. return self._get_default()
  636. @cached_property
  637. def _get_default(self):
  638. if self.has_default():
  639. if callable(self.default):
  640. return self.default
  641. return lambda: self.default
  642. if not self.empty_strings_allowed or self.null and not connection.features.interprets_empty_strings_as_nulls:
  643. return return_None
  644. return str # return empty string
  645. def get_choices(self, include_blank=True, blank_choice=BLANK_CHOICE_DASH, limit_choices_to=None):
  646. """
  647. Return choices with a default blank choices included, for use
  648. as <select> choices for this field.
  649. """
  650. if self.choices:
  651. choices = list(self.choices)
  652. if include_blank:
  653. blank_defined = any(choice in ('', None) for choice, _ in self.flatchoices)
  654. if not blank_defined:
  655. choices = blank_choice + choices
  656. return choices
  657. rel_model = self.remote_field.model
  658. limit_choices_to = limit_choices_to or self.get_limit_choices_to()
  659. choice_func = operator.attrgetter(
  660. self.remote_field.get_related_field().attname
  661. if hasattr(self.remote_field, 'get_related_field')
  662. else 'pk'
  663. )
  664. return (blank_choice if include_blank else []) + [
  665. (choice_func(x), smart_text(x))
  666. for x in rel_model._default_manager.complex_filter(limit_choices_to)
  667. ]
  668. def value_to_string(self, obj):
  669. """
  670. Return a string value of this field from the passed obj.
  671. This is used by the serialization framework.
  672. """
  673. return str(self.value_from_object(obj))
  674. def _get_flatchoices(self):
  675. """Flattened version of choices tuple."""
  676. flat = []
  677. for choice, value in self.choices:
  678. if isinstance(value, (list, tuple)):
  679. flat.extend(value)
  680. else:
  681. flat.append((choice, value))
  682. return flat
  683. flatchoices = property(_get_flatchoices)
  684. def save_form_data(self, instance, data):
  685. setattr(instance, self.name, data)
  686. def formfield(self, form_class=None, choices_form_class=None, **kwargs):
  687. """Return a django.forms.Field instance for this field."""
  688. defaults = {'required': not self.blank,
  689. 'label': capfirst(self.verbose_name),
  690. 'help_text': self.help_text}
  691. if self.has_default():
  692. if callable(self.default):
  693. defaults['initial'] = self.default
  694. defaults['show_hidden_initial'] = True
  695. else:
  696. defaults['initial'] = self.get_default()
  697. if self.choices:
  698. # Fields with choices get special treatment.
  699. include_blank = (self.blank or
  700. not (self.has_default() or 'initial' in kwargs))
  701. defaults['choices'] = self.get_choices(include_blank=include_blank)
  702. defaults['coerce'] = self.to_python
  703. if self.null:
  704. defaults['empty_value'] = None
  705. if choices_form_class is not None:
  706. form_class = choices_form_class
  707. else:
  708. form_class = forms.TypedChoiceField
  709. # Many of the subclass-specific formfield arguments (min_value,
  710. # max_value) don't apply for choice fields, so be sure to only pass
  711. # the values that TypedChoiceField will understand.
  712. for k in list(kwargs):
  713. if k not in ('coerce', 'empty_value', 'choices', 'required',
  714. 'widget', 'label', 'initial', 'help_text',
  715. 'error_messages', 'show_hidden_initial', 'disabled'):
  716. del kwargs[k]
  717. defaults.update(kwargs)
  718. if form_class is None:
  719. form_class = forms.CharField
  720. return form_class(**defaults)
  721. def value_from_object(self, obj):
  722. """Return the value of this field in the given model instance."""
  723. return getattr(obj, self.attname)

表关系的实现

  1. 一对多===>外键================>ForeignKeyField
  2. 一对一===>外键+唯一键===========>OneToOneField
  3. 多对多===>关联表:外键+联合唯一===>ManyToManyField

MySQL数据状态检查

  1. mysql> show databases;
  2. +--------------------+
  3. | Database |
  4. +--------------------+
  5. | book |
  6. | information_schema |
  7. +--------------------+
  8. 2 rows in set (0.03 sec)
  9. mysql> use book;
  10. Database changed
  11. mysql> show tables;
  12. +----------------------------+
  13. | Tables_in_book |
  14. +----------------------------+
  15. | auth_group |
  16. | auth_group_permissions |
  17. | auth_permission |
  18. | auth_user |
  19. | auth_user_groups |
  20. | auth_user_user_permissions |
  21. | django_admin_log |
  22. | django_content_type |
  23. | django_migrations |
  24. | django_session |
  25. | user |
  26. +----------------------------+
  27. 11 rows in set (0.01 sec)
  28. mysql> select * from user;
  29. +----+----------+-----+--------+
  30. | id | name | age | gender |
  31. +----+----------+-----+--------+
  32. | 1 | 徐媛老师 | 18 | 1 |
  33. | 2 | 小鱼儿 | 18 | 0 |
  34. | 3 | 熊猫TV | 18 | 0 |
  35. | 4 | 花无缺 | 18 | 1 |
  36. +----+----------+-----+--------+
  37. 4 rows in set (0.02 sec)

models.py编程

  1. class BookInfo(models.Model):
  2. name = models.CharField(max_length=26) # 一个数字两个字符,所以尽量用偶数
  3. book = models.ForeignKey('User', on_delete=models.CASCADE) # 级联删除,一删除则多也会删除---连根拔起
  4. class Meta:
  5. db_table = 'bookinfo'
  6. def __str__(self):
  7. return self.name

数据迁移过程

  1. (tzblog) C:\Users\41999\Documents\项目管理\duplicate\tzblog\Scripts\tzlook>python manage.py check
  2. C:\Users\41999\Documents\项目管理\duplicate\tzblog\Scripts\tzlook
  3. System check identified no issues (0 silenced).
  4. (tzblog) C:\Users\41999\Documents\项目管理\duplicate\tzblog\Scripts\tzlook>python manage.py makemigrations book
  5. C:\Users\41999\Documents\项目管理\duplicate\tzblog\Scripts\tzlook
  6. Migrations for 'book':
  7. book\migrations\0002_bookinfo.py
  8. - Create model BookInfo
  9. (tzblog) C:\Users\41999\Documents\项目管理\duplicate\tzblog\Scripts\tzlook>python manage.py migrate book
  10. C:\Users\41999\Documents\项目管理\duplicate\tzblog\Scripts\tzlook
  11. Operations to perform:
  12. Apply all migrations: book
  13. Running migrations:
  14. Applying book.0002_bookinfo... OK
  15. (tzblog) C:\Users\41999\Documents\项目管理\duplicate\tzblog\Scripts\tzlook>python manage.py sqlmigrate book 0002
  16. C:\Users\41999\Documents\项目管理\duplicate\tzblog\Scripts\tzlook
  17. BEGIN;
  18. --
  19. -- Create model BookInfo
  20. --
  21. CREATE TABLE `bookinfo` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `name` varchar(26) NOT NULL, `book_id` integer NOT NULL);
  22. ALTER TABLE `bookinfo` ADD CONSTRAINT `bookinfo_book_id_fe11563d_fk_user_id` FOREIGN KEY (`book_id`) REFERENCES `user` (`id`);
  23. COMMIT;

数据库检查数据迁移情况

  1. mysql> show databases;
  2. +--------------------+
  3. | Database |
  4. +--------------------+
  5. | book |
  6. | information_schema |
  7. +--------------------+
  8. 2 rows in set (0.00 sec)
  9. mysql> use book;
  10. Database changed
  11. mysql> show tables;
  12. +----------------------------+
  13. | Tables_in_book |
  14. +----------------------------+
  15. | auth_group |
  16. | auth_group_permissions |
  17. | auth_permission |
  18. | auth_user |
  19. | auth_user_groups |
  20. | auth_user_user_permissions |
  21. | bookinfo |
  22. | django_admin_log |
  23. | django_content_type |
  24. | django_migrations |
  25. | django_session |
  26. | user |
  27. +----------------------------+
  28. 12 rows in set (0.00 sec)
  29. mysql> select * from bookinfo;
  30. Empty set (0.00 sec)
  31. mysql> desc bookinfo;
  32. +---------+-------------+------+-----+---------+----------------+
  33. | Field | Type | Null | Key | Default | Extra |
  34. +---------+-------------+------+-----+---------+----------------+
  35. | id | int | NO | PRI | NULL | auto_increment |
  36. | name | varchar(26) | NO | | NULL | |
  37. | book_id | int | NO | MUL | NULL | |
  38. +---------+-------------+------+-----+---------+----------------+
  39. 3 rows in set (0.01 sec)

向表中增加数据

  1. ##前提:导入models中的BookInfo类
  2. ### models.py
  3. <-------------------------------------------------->
  4. class BookInfo(models.Model):
  5. name = models.CharField(max_length=26) # 一个数字两个字符,所以尽量用偶数
  6. book = models.ForeignKey('User', on_delete=models.CASCADE) # 级联删除,一删除则多也会删除---连根拔起
  7. class Meta:
  8. db_table = 'bookinfo'
  9. def __str__(self):
  10. return self.name
  11. <-------------------------------------------------->
  12. ### views.py
  13. def add_book(request):
  14. '''
  15. 添加书籍名称
  16. '''
  17. book = BookInfo(name='Python Django开发实战', book_id=1)
  18. book.save()
  19. return HttpResponse("书籍:Python Django开发实战, 已经添加成功")
  20. <-------------------------------------------------->
  21. ### urls.py
  22. path('add_book/', views.add_book, name='add_book'), # 向BookInfo表添加书名,直接以类而非方法/属性的方式

数据库查询验证数据状态

  1. mysql> desc bookinfo;
  2. +---------+-------------+------+-----+---------+----------------+
  3. | Field | Type | Null | Key | Default | Extra |
  4. +---------+-------------+------+-----+---------+----------------+
  5. | id | int | NO | PRI | NULL | auto_increment |
  6. | name | varchar(26) | NO | | NULL | |
  7. | book_id | int | NO | MUL | NULL | |
  8. +---------+-------------+------+-----+---------+----------------+
  9. 3 rows in set (0.01 sec)
  10. mysql> select * from bookinfo;
  11. +----+-----------------------+---------+
  12. | id | name | book_id |
  13. +----+-----------------------+---------+
  14. | 1 | Python Django开发实战 | 1 |
  15. +----+-----------------------+---------+
  16. 1 row in set (0.00 sec)
  17. mysql>

为数据库增加字段

  1. ### 增加的字段
  2. pub_date = models.DateField(verbose_name='发布日期’, nul1=True)
  3. readcount = models.IntegerField(default=0, verbose_name='阅读量')
  4. commentcount = models.IntegerField(default=0, verbose_name='评论量')
  5. is_delete = models.BooleanField(default=False, verbose_name='逻辑删除')
  6. ### 迁移过程
  7. (tzblog) C:\Users\41999\Documents\项目管理\duplicate\tzblog\Scripts\tzlook>python manage.py check
  8. C:\Users\41999\Documents\项目管理\duplicate\tzblog\Scripts\tzlook
  9. System check identified no issues (0 silenced).
  10. (tzblog) C:\Users\41999\Documents\项目管理\duplicate\tzblog\Scripts\tzlook>python manage.py makemigrations book
  11. C:\Users\41999\Documents\项目管理\duplicate\tzblog\Scripts\tzlook
  12. Migrations for 'book':
  13. book\migrations\0003_auto_20210706_1010.py
  14. - Add field comment_count to bookinfo
  15. - Add field is_delete to bookinfo
  16. - Add field pub_date to bookinfo
  17. - Add field read_count to bookinfo
  18. (tzblog) C:\Users\41999\Documents\项目管理\duplicate\tzblog\Scripts\tzlook>python manage.py migrate book
  19. C:\Users\41999\Documents\项目管理\duplicate\tzblog\Scripts\tzlook
  20. Operations to perform:
  21. Apply all migrations: book
  22. Running migrations:
  23. Applying book.0003_auto_20210706_1010... OK
  24. (tzblog) C:\Users\41999\Documents\项目管理\duplicate\tzblog\Scripts\tzlook>python manage.py sqlmigrate book 0003
  25. C:\Users\41999\Documents\项目管理\duplicate\tzblog\Scripts\tzlook
  26. BEGIN;
  27. --
  28. -- Add field comment_count to bookinfo
  29. --
  30. ALTER TABLE `bookinfo` ADD COLUMN `comment_count` integer DEFAULT 0 NOT NULL;
  31. ALTER TABLE `bookinfo` ALTER COLUMN `comment_count` DROP DEFAULT;
  32. --
  33. -- Add field is_delete to bookinfo
  34. --
  35. ALTER TABLE `bookinfo` ADD COLUMN `is_delete` bool DEFAULT 0 NOT NULL;
  36. ALTER TABLE `bookinfo` ALTER COLUMN `is_delete` DROP DEFAULT;
  37. --
  38. -- Add field pub_date to bookinfo
  39. --
  40. ALTER TABLE `bookinfo` ADD COLUMN `pub_date` date NULL;
  41. --
  42. -- Add field read_count to bookinfo
  43. --
  44. ALTER TABLE `bookinfo` ADD COLUMN `read_count` integer DEFAULT 0 NOT NULL;
  45. ALTER TABLE `bookinfo` ALTER COLUMN `read_count` DROP DEFAULT;
  46. COMMIT;
  47. (tzblog) C:\Users\41999\Documents\项目管理\duplicate\tzblog\Scripts\tzlook>
  48. ### 数据检查
  49. mysql> show databases;
  50. +--------------------+
  51. | Database |
  52. +--------------------+
  53. | book |
  54. | information_schema |
  55. +--------------------+
  56. 2 rows in set (0.00 sec)
  57. mysql> use book
  58. Database changed
  59. mysql> use book;
  60. Database changed
  61. mysql> show tables;
  62. +----------------------------+
  63. | Tables_in_book |
  64. +----------------------------+
  65. | auth_group |
  66. | auth_group_permissions |
  67. | auth_permission |
  68. | auth_user |
  69. | auth_user_groups |
  70. | auth_user_user_permissions |
  71. | bookinfo |
  72. | django_admin_log |
  73. | django_content_type |
  74. | django_migrations |
  75. | django_session |
  76. | user |
  77. +----------------------------+
  78. 12 rows in set (0.00 sec)
  79. mysql> desc bookinfo;
  80. +---------------+-------------+------+-----+---------+----------------+
  81. | Field | Type | Null | Key | Default | Extra |
  82. +---------------+-------------+------+-----+---------+----------------+
  83. | id | int | NO | PRI | NULL | auto_increment |
  84. | name | varchar(26) | NO | | NULL | |
  85. | book_id | int | NO | MUL | NULL | |
  86. | comment_count | int | NO | | NULL | |
  87. | is_delete | tinyint(1) | NO | | NULL | |
  88. | pub_date | date | YES | | NULL | |
  89. | read_count | int | NO | | NULL | |
  90. +---------------+-------------+------+-----+---------+----------------+
  91. 7 rows in set (0.00 sec)
  92. mysql> select * from bookinfo;
  93. +----+-----------------------+---------+---------------+-----------+----------+------------+
  94. | id | name | book_id | comment_count | is_delete | pub_date | read_count |
  95. +----+-----------------------+---------+---------------+-----------+----------+------------+
  96. | 1 | Python Django开发实战 | 1 | 0 | 0 | NULL | 0 |
  97. | 2 | 编程之美 | 2 | 0 | 0 | NULL | 0 |
  98. | 3 | 西西弗神话 | 3 | 0 | 0 | NULL | 0 |
  99. +----+-----------------------+---------+---------------+-----------+----------+------------+
  100. 3 rows in set (0.00 sec)
  101. mysql>

总结

常用查询方法

all()

get()

filter()

他们查询出来的都是对象

first()

last()

order_by()查询出来并且排序

常用模型字段类型

CharField 字符串类型

IntegerField 整型

Boolean 布尔类型

DateField 日期类型