常用查询方法
常用查询操作
###获取所有记录:
rs = User.objects.al1()
###获取第一条数据:
rs = User.objects.first()
###获取最后一条数据:
rs =user .objects.last()
###根据参数提供的条件获取过滤后的记录:
rs = User.objects.filter( name=" xiaoming" )
注意:filter(**kwargs)方法:根据参数提供的提取条件,获取一个过滤后的QuerySet
###排除name等于xiaoming的记录:
rs = User.objects.exclude ( name= "xiaoming " )
###获取一个记录对象:
rs = User.objects-get( name= " xiaoming")
###注意:get返回的对象具有唯一性质,如果符合条件的对象有多个,则get报错!
###对结果排序order_by :
rs-user .objects.order_by ("age" )
###多项排序:
rs =User.objects.order_by( " age" ,'id " )
###逆向排序:
rs =User .objects.order_by (" -age")
###将返回来的Queryset中的Mode1转换为字典
rs =User .objects.all().values()
###获取当前查询到的娄数据的总娄女:
rs =User .objects.count()
常用查询条件
###exact相当于等于号:
rs = User.objects.filter( name__exact= "xiaoming' )
###iexact:跟exact,只是忽略大小写的匹配。
###contains包含:
rs = User.objects.filter( name__contains="xiao)
##icontains跟contains,唯—不同是忽略大小写。
###startwith 以什么开始:
rs = User.objects.filter( name__startswith= 'xiao")
###istartswith :同startswith,忽略大小写。
###endswith :司startswith,以什么结尾。
###iendswith :同istartswith,以什么结尾,忽略大小写。
###in成员所属:
rs - User.objects.filter(age__in=[ 18,19,20])
gt大于:
rs = User.objects.filter(age__gt=2e)
gte大于等于:
rs - User.objects.filter(age__gte=20)
lt小于:
rs = User.objects.filter(age__lt=2e)
lte小于等于:
rs - User.objects.filter(age__lte=20)
range区间:
rs - user.objects.filter(age__range=(18,20))
isnul1 判断是否为空:|
rs = User.objects.filter(city__isnull=True)
常用字段类型的映射关系
### int =============> lntegetField
### varchar==========> CharField
### longtext=========> TextField
### date ============> DateField
### DateTimeField ===> datetime
字段源码阅读
class BooleanField(Field):
empty_strings_allowed = False
default_error_messages = {
'invalid': _("'%(value)s' value must be either True or False."),
'invalid_nullable': _("'%(value)s' value must be either True, False, or None."),
}
description = _("Boolean (Either True or False)")
def get_internal_type(self):
return "BooleanField"
def to_python(self, value):
if self.null and value in self.empty_values:
return None
if value in (True, False):
# if value is 1 or 0 than it's equal to True or False, but we want
# to return a true bool for semantic reasons. # semantic---语义的
return bool(value)
# 兼容性:容许三种输入值
if value in ('t', 'True', '1'):
return True
if value in ('f', 'False', '0'):
return False
raise exceptions.ValidationError(
self.error_messages['invalid_nullable' if self.null else 'invalid'],
code='invalid',
params={'value': value},
)
def get_prep_value(self, value):
value = super().get_prep_value(value)
if value is None:
return None
return self.to_python(value)
class CharField(Field):
description = _("String (up to %(max_length)s)")
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.validators.append(validators.MaxLengthValidator(self.max_length))
def check(self, **kwargs):
return [
*super().check(**kwargs),
*self._check_max_length_attribute(**kwargs),
]
def _check_max_length_attribute(self, **kwargs):
if self.max_length is None:
return [
checks.Error(
"CharFields must define a 'max_length' attribute.",
obj=self,
id='fields.E120',
)
]
elif (not isinstance(self.max_length, int) or isinstance(self.max_length, bool) or
self.max_length <= 0):
return [
checks.Error(
"'max_length' must be a positive integer.",
obj=self,
id='fields.E121',
)
]
else:
return []
def cast_db_type(self, connection):
if self.max_length is None:
return connection.ops.cast_char_field_without_max_length
return super().cast_db_type(connection)
def get_internal_type(self):
return "CharField"
def to_python(self, value):
if isinstance(value, str) or value is None:
return value
return str(value)
def get_prep_value(self, value):
value = super().get_prep_value(value)
return self.to_python(value)
def formfield(self, **kwargs):
# Passing max_length to forms.CharField means that the value's length
# will be validated twice. This is considered acceptable since we want
# the value in the form field (to pass into widget for example).
defaults = {'max_length': self.max_length}
# TODO: Handle multiple backends with different feature flags.
if self.null and not connection.features.interprets_empty_strings_as_nulls:
defaults['empty_value'] = None
defaults.update(kwargs)
return super().formfield(**defaults)
常用的模型字段类型
常用字段类型
1.IntegerField :整型,映射到数据库中的int类型。
2.CharField:字符类型,映射到数据库中的varchar类型,通过max_length指定最大长度。
3.TextField:文本类型,映射到数据库中的text类型。
4.BooleanField:布尔类型,映射到数据库中的tinyint类型,在使用的时候,传递True/False进去。如果要可以为空,则用NullBooleanField。
5.DateField:日期类型,没有时间。映射到数据库中是date类型,
在使用的时候,可以设置DateField.auto_now每次保存对象时,自动设置该字段为当前时间。设置DateField.auto_now_add当对象第一次被创建时自动设置当前时间。
6.DateTimeField:日期时间类型。映射到数据库中的是datetime类型,在使用的时候,传递datetime.datetime()进去。
Field常用参数
primary_key:指定是否为主键。
unique:指定是否唯一。
null:指定是否为空,默认为False。
blank:等于True时form表单验证时可以为空,默认为False。
default:设置默认值。
DateField.auto now:每次修改都会将当前时间更新进去,只有调用,QuerySet.update方法将不会调用。这个参数只是Date和DateTime以及TimModel.save()方法才会调用e类才有的。
DateField.auto _now add: 第一次添加进去,都会将当前时间设置进去。以后修改,不会修改这个值
Field的常用操作和表关系的实现
Field 源码
@total_ordering
class Field(RegisterLookupMixin):
"""Base class for all field types"""
# Designates whether empty strings fundamentally are allowed at the
# database level.
empty_strings_allowed = True
empty_values = list(validators.EMPTY_VALUES)
# These track each time a Field instance is created. Used to retain order.
# The auto_creation_counter is used for fields that Django implicitly
# creates, creation_counter is used for all user-specified fields.
creation_counter = 0
auto_creation_counter = -1
default_validators = [] # Default set of validators
default_error_messages = {
'invalid_choice': _('Value %(value)r is not a valid choice.'),
'null': _('This field cannot be null.'),
'blank': _('This field cannot be blank.'),
'unique': _('%(model_name)s with this %(field_label)s '
'already exists.'),
# Translators: The 'lookup_type' is one of 'date', 'year' or 'month'.
# Eg: "Title must be unique for pub_date year"
'unique_for_date': _("%(field_label)s must be unique for "
"%(date_field_label)s %(lookup_type)s."),
}
system_check_deprecated_details = None
system_check_removed_details = None
# Field flags
hidden = False
many_to_many = None
many_to_one = None
one_to_many = None
one_to_one = None
related_model = None
# Generic field type description, usually overridden by subclasses
def _description(self):
return _('Field of type: %(field_type)s') % {
'field_type': self.__class__.__name__
}
description = property(_description)
def __init__(self, verbose_name=None, name=None, primary_key=False,
max_length=None, unique=False, blank=False, null=False,
db_index=False, rel=None, default=NOT_PROVIDED, editable=True,
serialize=True, unique_for_date=None, unique_for_month=None,
unique_for_year=None, choices=None, help_text='', db_column=None,
db_tablespace=None, auto_created=False, validators=(),
error_messages=None):
self.name = name
self.verbose_name = verbose_name # May be set by set_attributes_from_name
self._verbose_name = verbose_name # Store original for deconstruction
self.primary_key = primary_key
self.max_length, self._unique = max_length, unique
self.blank, self.null = blank, null
self.remote_field = rel
self.is_relation = self.remote_field is not None
self.default = default
self.editable = editable
self.serialize = serialize
self.unique_for_date = unique_for_date
self.unique_for_month = unique_for_month
self.unique_for_year = unique_for_year
if isinstance(choices, collections.abc.Iterator):
choices = list(choices)
self.choices = choices or []
self.help_text = help_text
self.db_index = db_index
self.db_column = db_column
self._db_tablespace = db_tablespace
self.auto_created = auto_created
# Adjust the appropriate creation counter, and save our local copy.
if auto_created:
self.creation_counter = Field.auto_creation_counter
Field.auto_creation_counter -= 1
else:
self.creation_counter = Field.creation_counter
Field.creation_counter += 1
self._validators = list(validators) # Store for deconstruction later
messages = {}
for c in reversed(self.__class__.__mro__):
messages.update(getattr(c, 'default_error_messages', {}))
messages.update(error_messages or {})
self._error_messages = error_messages # Store for deconstruction later
self.error_messages = messages
def __str__(self):
"""
Return "app_label.model_label.field_name" for fields attached to
models.
"""
if not hasattr(self, 'model'):
return super().__str__()
model = self.model
app = model._meta.app_label
return '%s.%s.%s' % (app, model._meta.object_name, self.name)
def __repr__(self):
"""Display the module, class, and name of the field."""
path = '%s.%s' % (self.__class__.__module__, self.__class__.__qualname__)
name = getattr(self, 'name', None)
if name is not None:
return '<%s: %s>' % (path, name)
return '<%s>' % path
def check(self, **kwargs):
return [
*self._check_field_name(),
*self._check_choices(),
*self._check_db_index(),
*self._check_null_allowed_for_primary_keys(),
*self._check_backend_specific_checks(**kwargs),
*self._check_validators(),
*self._check_deprecation_details(),
]
def _check_field_name(self):
"""
Check if field name is valid, i.e. 1) does not end with an
underscore, 2) does not contain "__" and 3) is not "pk".
"""
if self.name.endswith('_'):
return [
checks.Error(
'Field names must not end with an underscore.',
obj=self,
id='fields.E001',
)
]
elif LOOKUP_SEP in self.name:
return [
checks.Error(
'Field names must not contain "%s".' % (LOOKUP_SEP,),
obj=self,
id='fields.E002',
)
]
elif self.name == 'pk':
return [
checks.Error(
"'pk' is a reserved word that cannot be used as a field name.",
obj=self,
id='fields.E003',
)
]
else:
return []
def _check_choices(self):
if not self.choices:
return []
def is_value(value, accept_promise=True):
return isinstance(value, (str, Promise) if accept_promise else str) or not is_iterable(value)
if is_value(self.choices, accept_promise=False):
return [
checks.Error(
"'choices' must be an iterable (e.g., a list or tuple).",
obj=self,
id='fields.E004',
)
]
# Expect [group_name, [value, display]]
for choices_group in self.choices:
try:
group_name, group_choices = choices_group
except ValueError:
# Containing non-pairs
break
try:
if not all(
is_value(value) and is_value(human_name)
for value, human_name in group_choices
):
break
except (TypeError, ValueError):
# No groups, choices in the form [value, display]
value, human_name = group_name, group_choices
if not is_value(value) or not is_value(human_name):
break
# Special case: choices=['ab']
if isinstance(choices_group, str):
break
else:
return []
return [
checks.Error(
"'choices' must be an iterable containing "
"(actual value, human readable name) tuples.",
obj=self,
id='fields.E005',
)
]
def _check_db_index(self):
if self.db_index not in (None, True, False):
return [
checks.Error(
"'db_index' must be None, True or False.",
obj=self,
id='fields.E006',
)
]
else:
return []
def _check_null_allowed_for_primary_keys(self):
if (self.primary_key and self.null and
not connection.features.interprets_empty_strings_as_nulls):
# We cannot reliably check this for backends like Oracle which
# consider NULL and '' to be equal (and thus set up
# character-based fields a little differently).
return [
checks.Error(
'Primary keys must not have null=True.',
hint=('Set null=False on the field, or '
'remove primary_key=True argument.'),
obj=self,
id='fields.E007',
)
]
else:
return []
def _check_backend_specific_checks(self, **kwargs):
app_label = self.model._meta.app_label
for db in connections:
if router.allow_migrate(db, app_label, model_name=self.model._meta.model_name):
return connections[db].validation.check_field(self, **kwargs)
return []
def _check_validators(self):
errors = []
for i, validator in enumerate(self.validators):
if not callable(validator):
errors.append(
checks.Error(
"All 'validators' must be callable.",
hint=(
"validators[{i}] ({repr}) isn't a function or "
"instance of a validator class.".format(
i=i, repr=repr(validator),
)
),
obj=self,
id='fields.E008',
)
)
return errors
def _check_deprecation_details(self):
if self.system_check_removed_details is not None:
return [
checks.Error(
self.system_check_removed_details.get(
'msg',
'%s has been removed except for support in historical '
'migrations.' % self.__class__.__name__
),
hint=self.system_check_removed_details.get('hint'),
obj=self,
id=self.system_check_removed_details.get('id', 'fields.EXXX'),
)
]
elif self.system_check_deprecated_details is not None:
return [
checks.Warning(
self.system_check_deprecated_details.get(
'msg',
'%s has been deprecated.' % self.__class__.__name__
),
hint=self.system_check_deprecated_details.get('hint'),
obj=self,
id=self.system_check_deprecated_details.get('id', 'fields.WXXX'),
)
]
return []
def get_col(self, alias, output_field=None):
if output_field is None:
output_field = self
if alias != self.model._meta.db_table or output_field != self:
from django.db.models.expressions import Col
return Col(alias, self, output_field)
else:
return self.cached_col
@cached_property
def cached_col(self):
from django.db.models.expressions import Col
return Col(self.model._meta.db_table, self)
def select_format(self, compiler, sql, params):
"""
Custom format for select clauses. For example, GIS columns need to be
selected as AsText(table.col) on MySQL as the table.col data can't be
used by Django.
"""
return sql, params
def deconstruct(self):
"""
Return enough information to recreate the field as a 4-tuple:
* The name of the field on the model, if contribute_to_class() has
been run.
* The import path of the field, including the class:e.g.
django.db.models.IntegerField This should be the most portable
version, so less specific may be better.
* A list of positional arguments.
* A dict of keyword arguments.
Note that the positional or keyword arguments must contain values of
the following types (including inner values of collection types):
* None, bool, str, int, float, complex, set, frozenset, list, tuple,
dict
* UUID
* datetime.datetime (naive), datetime.date
* top-level classes, top-level functions - will be referenced by their
full import path
* Storage instances - these have their own deconstruct() method
This is because the values here must be serialized into a text format
(possibly new Python code, possibly JSON) and these are the only types
with encoding handlers defined.
There's no need to return the exact way the field was instantiated this
time, just ensure that the resulting field is the same - prefer keyword
arguments over positional ones, and omit parameters with their default
values.
"""
# Short-form way of fetching all the default parameters
keywords = {}
possibles = {
"verbose_name": None,
"primary_key": False,
"max_length": None,
"unique": False,
"blank": False,
"null": False,
"db_index": False,
"default": NOT_PROVIDED,
"editable": True,
"serialize": True,
"unique_for_date": None,
"unique_for_month": None,
"unique_for_year": None,
"choices": [],
"help_text": '',
"db_column": None,
"db_tablespace": None,
"auto_created": False,
"validators": [],
"error_messages": None,
}
attr_overrides = {
"unique": "_unique",
"error_messages": "_error_messages",
"validators": "_validators",
"verbose_name": "_verbose_name",
"db_tablespace": "_db_tablespace",
}
equals_comparison = {"choices", "validators"}
for name, default in possibles.items():
value = getattr(self, attr_overrides.get(name, name))
# Unroll anything iterable for choices into a concrete list
if name == "choices" and isinstance(value, collections.abc.Iterable):
value = list(value)
# Do correct kind of comparison
if name in equals_comparison:
if value != default:
keywords[name] = value
else:
if value is not default:
keywords[name] = value
# Work out path - we shorten it for known Django core fields
path = "%s.%s" % (self.__class__.__module__, self.__class__.__qualname__)
if path.startswith("django.db.models.fields.related"):
path = path.replace("django.db.models.fields.related", "django.db.models")
if path.startswith("django.db.models.fields.files"):
path = path.replace("django.db.models.fields.files", "django.db.models")
if path.startswith("django.db.models.fields.proxy"):
path = path.replace("django.db.models.fields.proxy", "django.db.models")
if path.startswith("django.db.models.fields"):
path = path.replace("django.db.models.fields", "django.db.models")
# Return basic info - other fields should override this.
return (self.name, path, [], keywords)
def clone(self):
"""
Uses deconstruct() to clone a new copy of this Field.
Will not preserve any class attachments/attribute names.
"""
name, path, args, kwargs = self.deconstruct()
return self.__class__(*args, **kwargs)
def __eq__(self, other):
# Needed for @total_ordering
if isinstance(other, Field):
return self.creation_counter == other.creation_counter
return NotImplemented
def __lt__(self, other):
# This is needed because bisect does not take a comparison function.
if isinstance(other, Field):
return self.creation_counter < other.creation_counter
return NotImplemented
def __hash__(self):
return hash(self.creation_counter)
def __deepcopy__(self, memodict):
# We don't have to deepcopy very much here, since most things are not
# intended to be altered after initial creation.
obj = copy.copy(self)
if self.remote_field:
obj.remote_field = copy.copy(self.remote_field)
if hasattr(self.remote_field, 'field') and self.remote_field.field is self:
obj.remote_field.field = obj
memodict[id(self)] = obj
return obj
def __copy__(self):
# We need to avoid hitting __reduce__, so define this
# slightly weird copy construct.
obj = Empty()
obj.__class__ = self.__class__
obj.__dict__ = self.__dict__.copy()
return obj
def __reduce__(self):
"""
Pickling should return the model._meta.fields instance of the field,
not a new copy of that field. So, use the app registry to load the
model and then the field back.
"""
if not hasattr(self, 'model'):
# Fields are sometimes used without attaching them to models (for
# example in aggregation). In this case give back a plain field
# instance. The code below will create a new empty instance of
# class self.__class__, then update its dict with self.__dict__
# values - so, this is very close to normal pickle.
state = self.__dict__.copy()
# The _get_default cached_property can't be pickled due to lambda
# usage.
state.pop('_get_default', None)
return _empty, (self.__class__,), state
return _load_field, (self.model._meta.app_label, self.model._meta.object_name,
self.name)
def get_pk_value_on_save(self, instance):
"""
Hook to generate new PK values on save. This method is called when
saving instances with no primary key value set. If this method returns
something else than None, then the returned value is used when saving
the new instance.
"""
if self.default:
return self.get_default()
return None
def to_python(self, value):
"""
Convert the input value into the expected Python data type, raising
django.core.exceptions.ValidationError if the data can't be converted.
Return the converted value. Subclasses should override this.
"""
return value
@cached_property
def validators(self):
"""
Some validators can't be created at field initialization time.
This method provides a way to delay their creation until required.
"""
return [*self.default_validators, *self._validators]
def run_validators(self, value):
if value in self.empty_values:
return
errors = []
for v in self.validators:
try:
v(value)
except exceptions.ValidationError as e:
if hasattr(e, 'code') and e.code in self.error_messages:
e.message = self.error_messages[e.code]
errors.extend(e.error_list)
if errors:
raise exceptions.ValidationError(errors)
def validate(self, value, model_instance):
"""
Validate value and raise ValidationError if necessary. Subclasses
should override this to provide validation logic.
"""
if not self.editable:
# Skip validation for non-editable fields.
return
if self.choices and value not in self.empty_values:
for option_key, option_value in self.choices:
if isinstance(option_value, (list, tuple)):
# This is an optgroup, so look inside the group for
# options.
for optgroup_key, optgroup_value in option_value:
if value == optgroup_key:
return
elif value == option_key:
return
raise exceptions.ValidationError(
self.error_messages['invalid_choice'],
code='invalid_choice',
params={'value': value},
)
if value is None and not self.null:
raise exceptions.ValidationError(self.error_messages['null'], code='null')
if not self.blank and value in self.empty_values:
raise exceptions.ValidationError(self.error_messages['blank'], code='blank')
def clean(self, value, model_instance):
"""
Convert the value's type and run validation. Validation errors
from to_python() and validate() are propagated. Return the correct
value if no error is raised.
"""
value = self.to_python(value)
self.validate(value, model_instance)
self.run_validators(value)
return value
def db_type_parameters(self, connection):
return DictWrapper(self.__dict__, connection.ops.quote_name, 'qn_')
def db_check(self, connection):
"""
Return the database column check constraint for this field, for the
provided connection. Works the same way as db_type() for the case that
get_internal_type() does not map to a preexisting model field.
"""
data = self.db_type_parameters(connection)
try:
return connection.data_type_check_constraints[self.get_internal_type()] % data
except KeyError:
return None
def db_type(self, connection):
"""
Return the database column data type for this field, for the provided
connection.
"""
# The default implementation of this method looks at the
# backend-specific data_types dictionary, looking up the field by its
# "internal type".
#
# A Field class can implement the get_internal_type() method to specify
# which *preexisting* Django Field class it's most similar to -- i.e.,
# a custom field might be represented by a TEXT column type, which is
# the same as the TextField Django field type, which means the custom
# field's get_internal_type() returns 'TextField'.
#
# But the limitation of the get_internal_type() / data_types approach
# is that it cannot handle database column types that aren't already
# mapped to one of the built-in Django field types. In this case, you
# can implement db_type() instead of get_internal_type() to specify
# exactly which wacky database column type you want to use.
data = self.db_type_parameters(connection)
try:
return connection.data_types[self.get_internal_type()] % data
except KeyError:
return None
def rel_db_type(self, connection):
"""
Return the data type that a related field pointing to this field should
use. For example, this method is called by ForeignKey and OneToOneField
to determine its data type.
"""
return self.db_type(connection)
def cast_db_type(self, connection):
"""Return the data type to use in the Cast() function."""
db_type = connection.ops.cast_data_types.get(self.get_internal_type())
if db_type:
return db_type % self.db_type_parameters(connection)
return self.db_type(connection)
def db_parameters(self, connection):
"""
Extension of db_type(), providing a range of different return values
(type, checks). This will look at db_type(), allowing custom model
fields to override it.
"""
type_string = self.db_type(connection)
check_string = self.db_check(connection)
return {
"type": type_string,
"check": check_string,
}
def db_type_suffix(self, connection):
return connection.data_types_suffix.get(self.get_internal_type())
def get_db_converters(self, connection):
if hasattr(self, 'from_db_value'):
return [self.from_db_value]
return []
@property
def unique(self):
return self._unique or self.primary_key
@property
def db_tablespace(self):
return self._db_tablespace or settings.DEFAULT_INDEX_TABLESPACE
def set_attributes_from_name(self, name):
self.name = self.name or name
self.attname, self.column = self.get_attname_column()
self.concrete = self.column is not None
if self.verbose_name is None and self.name:
self.verbose_name = self.name.replace('_', ' ')
def contribute_to_class(self, cls, name, private_only=False):
"""
Register the field with the model class it belongs to.
If private_only is True, create a separate instance of this field
for every subclass of cls, even if cls is not an abstract model.
"""
self.set_attributes_from_name(name)
self.model = cls
if private_only:
cls._meta.add_field(self, private=True)
else:
cls._meta.add_field(self)
if self.column:
# Don't override classmethods with the descriptor. This means that
# if you have a classmethod and a field with the same name, then
# such fields can't be deferred (we don't have a check for this).
if not getattr(cls, self.attname, None):
setattr(cls, self.attname, DeferredAttribute(self.attname))
if self.choices:
setattr(cls, 'get_%s_display' % self.name,
partialmethod(cls._get_FIELD_display, field=self))
def get_filter_kwargs_for_object(self, obj):
"""
Return a dict that when passed as kwargs to self.model.filter(), would
yield all instances having the same value for this field as obj has.
"""
return {self.name: getattr(obj, self.attname)}
def get_attname(self):
return self.name
def get_attname_column(self):
attname = self.get_attname()
column = self.db_column or attname
return attname, column
def get_internal_type(self):
return self.__class__.__name__
def pre_save(self, model_instance, add):
"""Return field's value just before saving."""
return getattr(model_instance, self.attname)
def get_prep_value(self, value):
"""Perform preliminary non-db specific value checks and conversions."""
if isinstance(value, Promise):
value = value._proxy____cast()
return value
def get_db_prep_value(self, value, connection, prepared=False):
"""
Return field's value prepared for interacting with the database backend.
Used by the default implementations of get_db_prep_save().
"""
if not prepared:
value = self.get_prep_value(value)
return value
def get_db_prep_save(self, value, connection):
"""Return field's value prepared for saving into a database."""
return self.get_db_prep_value(value, connection=connection, prepared=False)
def has_default(self):
"""Return a boolean of whether this field has a default value."""
return self.default is not NOT_PROVIDED
def get_default(self):
"""Return the default value for this field."""
return self._get_default()
@cached_property
def _get_default(self):
if self.has_default():
if callable(self.default):
return self.default
return lambda: self.default
if not self.empty_strings_allowed or self.null and not connection.features.interprets_empty_strings_as_nulls:
return return_None
return str # return empty string
def get_choices(self, include_blank=True, blank_choice=BLANK_CHOICE_DASH, limit_choices_to=None):
"""
Return choices with a default blank choices included, for use
as <select> choices for this field.
"""
if self.choices:
choices = list(self.choices)
if include_blank:
blank_defined = any(choice in ('', None) for choice, _ in self.flatchoices)
if not blank_defined:
choices = blank_choice + choices
return choices
rel_model = self.remote_field.model
limit_choices_to = limit_choices_to or self.get_limit_choices_to()
choice_func = operator.attrgetter(
self.remote_field.get_related_field().attname
if hasattr(self.remote_field, 'get_related_field')
else 'pk'
)
return (blank_choice if include_blank else []) + [
(choice_func(x), smart_text(x))
for x in rel_model._default_manager.complex_filter(limit_choices_to)
]
def value_to_string(self, obj):
"""
Return a string value of this field from the passed obj.
This is used by the serialization framework.
"""
return str(self.value_from_object(obj))
def _get_flatchoices(self):
"""Flattened version of choices tuple."""
flat = []
for choice, value in self.choices:
if isinstance(value, (list, tuple)):
flat.extend(value)
else:
flat.append((choice, value))
return flat
flatchoices = property(_get_flatchoices)
def save_form_data(self, instance, data):
setattr(instance, self.name, data)
def formfield(self, form_class=None, choices_form_class=None, **kwargs):
"""Return a django.forms.Field instance for this field."""
defaults = {'required': not self.blank,
'label': capfirst(self.verbose_name),
'help_text': self.help_text}
if self.has_default():
if callable(self.default):
defaults['initial'] = self.default
defaults['show_hidden_initial'] = True
else:
defaults['initial'] = self.get_default()
if self.choices:
# Fields with choices get special treatment.
include_blank = (self.blank or
not (self.has_default() or 'initial' in kwargs))
defaults['choices'] = self.get_choices(include_blank=include_blank)
defaults['coerce'] = self.to_python
if self.null:
defaults['empty_value'] = None
if choices_form_class is not None:
form_class = choices_form_class
else:
form_class = forms.TypedChoiceField
# Many of the subclass-specific formfield arguments (min_value,
# max_value) don't apply for choice fields, so be sure to only pass
# the values that TypedChoiceField will understand.
for k in list(kwargs):
if k not in ('coerce', 'empty_value', 'choices', 'required',
'widget', 'label', 'initial', 'help_text',
'error_messages', 'show_hidden_initial', 'disabled'):
del kwargs[k]
defaults.update(kwargs)
if form_class is None:
form_class = forms.CharField
return form_class(**defaults)
def value_from_object(self, obj):
"""Return the value of this field in the given model instance."""
return getattr(obj, self.attname)
表关系的实现
一对多===>外键================>ForeignKeyField
一对一===>外键+唯一键===========>OneToOneField
多对多===>关联表:外键+联合唯一===>ManyToManyField
MySQL数据状态检查
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| book |
| information_schema |
+--------------------+
2 rows in set (0.03 sec)
mysql> use book;
Database changed
mysql> show tables;
+----------------------------+
| Tables_in_book |
+----------------------------+
| auth_group |
| auth_group_permissions |
| auth_permission |
| auth_user |
| auth_user_groups |
| auth_user_user_permissions |
| django_admin_log |
| django_content_type |
| django_migrations |
| django_session |
| user |
+----------------------------+
11 rows in set (0.01 sec)
mysql> select * from user;
+----+----------+-----+--------+
| id | name | age | gender |
+----+----------+-----+--------+
| 1 | 徐媛老师 | 18 | 1 |
| 2 | 小鱼儿 | 18 | 0 |
| 3 | 熊猫TV | 18 | 0 |
| 4 | 花无缺 | 18 | 1 |
+----+----------+-----+--------+
4 rows in set (0.02 sec)
models.py编程
class BookInfo(models.Model):
name = models.CharField(max_length=26) # 一个数字两个字符,所以尽量用偶数
book = models.ForeignKey('User', on_delete=models.CASCADE) # 级联删除,一删除则多也会删除---连根拔起
class Meta:
db_table = 'bookinfo'
def __str__(self):
return self.name
数据迁移过程
(tzblog) C:\Users\41999\Documents\项目管理\duplicate\tzblog\Scripts\tzlook>python manage.py check
C:\Users\41999\Documents\项目管理\duplicate\tzblog\Scripts\tzlook
System check identified no issues (0 silenced).
(tzblog) C:\Users\41999\Documents\项目管理\duplicate\tzblog\Scripts\tzlook>python manage.py makemigrations book
C:\Users\41999\Documents\项目管理\duplicate\tzblog\Scripts\tzlook
Migrations for 'book':
book\migrations\0002_bookinfo.py
- Create model BookInfo
(tzblog) C:\Users\41999\Documents\项目管理\duplicate\tzblog\Scripts\tzlook>python manage.py migrate book
C:\Users\41999\Documents\项目管理\duplicate\tzblog\Scripts\tzlook
Operations to perform:
Apply all migrations: book
Running migrations:
Applying book.0002_bookinfo... OK
(tzblog) C:\Users\41999\Documents\项目管理\duplicate\tzblog\Scripts\tzlook>python manage.py sqlmigrate book 0002
C:\Users\41999\Documents\项目管理\duplicate\tzblog\Scripts\tzlook
BEGIN;
--
-- Create model BookInfo
--
CREATE TABLE `bookinfo` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `name` varchar(26) NOT NULL, `book_id` integer NOT NULL);
ALTER TABLE `bookinfo` ADD CONSTRAINT `bookinfo_book_id_fe11563d_fk_user_id` FOREIGN KEY (`book_id`) REFERENCES `user` (`id`);
COMMIT;
数据库检查数据迁移情况
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| book |
| information_schema |
+--------------------+
2 rows in set (0.00 sec)
mysql> use book;
Database changed
mysql> show tables;
+----------------------------+
| Tables_in_book |
+----------------------------+
| auth_group |
| auth_group_permissions |
| auth_permission |
| auth_user |
| auth_user_groups |
| auth_user_user_permissions |
| bookinfo |
| django_admin_log |
| django_content_type |
| django_migrations |
| django_session |
| user |
+----------------------------+
12 rows in set (0.00 sec)
mysql> select * from bookinfo;
Empty set (0.00 sec)
mysql> desc bookinfo;
+---------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------+-------------+------+-----+---------+----------------+
| id | int | NO | PRI | NULL | auto_increment |
| name | varchar(26) | NO | | NULL | |
| book_id | int | NO | MUL | NULL | |
+---------+-------------+------+-----+---------+----------------+
3 rows in set (0.01 sec)
向表中增加数据
##前提:导入models中的BookInfo类
### models.py
<-------------------------------------------------->
class BookInfo(models.Model):
name = models.CharField(max_length=26) # 一个数字两个字符,所以尽量用偶数
book = models.ForeignKey('User', on_delete=models.CASCADE) # 级联删除,一删除则多也会删除---连根拔起
class Meta:
db_table = 'bookinfo'
def __str__(self):
return self.name
<-------------------------------------------------->
### views.py
def add_book(request):
'''
添加书籍名称
'''
book = BookInfo(name='Python Django开发实战', book_id=1)
book.save()
return HttpResponse("书籍:Python Django开发实战, 已经添加成功")
<-------------------------------------------------->
### urls.py
path('add_book/', views.add_book, name='add_book'), # 向BookInfo表添加书名,直接以类而非方法/属性的方式
数据库查询验证数据状态
mysql> desc bookinfo;
+---------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------+-------------+------+-----+---------+----------------+
| id | int | NO | PRI | NULL | auto_increment |
| name | varchar(26) | NO | | NULL | |
| book_id | int | NO | MUL | NULL | |
+---------+-------------+------+-----+---------+----------------+
3 rows in set (0.01 sec)
mysql> select * from bookinfo;
+----+-----------------------+---------+
| id | name | book_id |
+----+-----------------------+---------+
| 1 | Python Django开发实战 | 1 |
+----+-----------------------+---------+
1 row in set (0.00 sec)
mysql>
为数据库增加字段
### 增加的字段
pub_date = models.DateField(verbose_name='发布日期’, nul1=True)
readcount = models.IntegerField(default=0, verbose_name='阅读量')
commentcount = models.IntegerField(default=0, verbose_name='评论量')
is_delete = models.BooleanField(default=False, verbose_name='逻辑删除')
### 迁移过程
(tzblog) C:\Users\41999\Documents\项目管理\duplicate\tzblog\Scripts\tzlook>python manage.py check
C:\Users\41999\Documents\项目管理\duplicate\tzblog\Scripts\tzlook
System check identified no issues (0 silenced).
(tzblog) C:\Users\41999\Documents\项目管理\duplicate\tzblog\Scripts\tzlook>python manage.py makemigrations book
C:\Users\41999\Documents\项目管理\duplicate\tzblog\Scripts\tzlook
Migrations for 'book':
book\migrations\0003_auto_20210706_1010.py
- Add field comment_count to bookinfo
- Add field is_delete to bookinfo
- Add field pub_date to bookinfo
- Add field read_count to bookinfo
(tzblog) C:\Users\41999\Documents\项目管理\duplicate\tzblog\Scripts\tzlook>python manage.py migrate book
C:\Users\41999\Documents\项目管理\duplicate\tzblog\Scripts\tzlook
Operations to perform:
Apply all migrations: book
Running migrations:
Applying book.0003_auto_20210706_1010... OK
(tzblog) C:\Users\41999\Documents\项目管理\duplicate\tzblog\Scripts\tzlook>python manage.py sqlmigrate book 0003
C:\Users\41999\Documents\项目管理\duplicate\tzblog\Scripts\tzlook
BEGIN;
--
-- Add field comment_count to bookinfo
--
ALTER TABLE `bookinfo` ADD COLUMN `comment_count` integer DEFAULT 0 NOT NULL;
ALTER TABLE `bookinfo` ALTER COLUMN `comment_count` DROP DEFAULT;
--
-- Add field is_delete to bookinfo
--
ALTER TABLE `bookinfo` ADD COLUMN `is_delete` bool DEFAULT 0 NOT NULL;
ALTER TABLE `bookinfo` ALTER COLUMN `is_delete` DROP DEFAULT;
--
-- Add field pub_date to bookinfo
--
ALTER TABLE `bookinfo` ADD COLUMN `pub_date` date NULL;
--
-- Add field read_count to bookinfo
--
ALTER TABLE `bookinfo` ADD COLUMN `read_count` integer DEFAULT 0 NOT NULL;
ALTER TABLE `bookinfo` ALTER COLUMN `read_count` DROP DEFAULT;
COMMIT;
(tzblog) C:\Users\41999\Documents\项目管理\duplicate\tzblog\Scripts\tzlook>
### 数据检查
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| book |
| information_schema |
+--------------------+
2 rows in set (0.00 sec)
mysql> use book
Database changed
mysql> use book;
Database changed
mysql> show tables;
+----------------------------+
| Tables_in_book |
+----------------------------+
| auth_group |
| auth_group_permissions |
| auth_permission |
| auth_user |
| auth_user_groups |
| auth_user_user_permissions |
| bookinfo |
| django_admin_log |
| django_content_type |
| django_migrations |
| django_session |
| user |
+----------------------------+
12 rows in set (0.00 sec)
mysql> desc bookinfo;
+---------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------------+-------------+------+-----+---------+----------------+
| id | int | NO | PRI | NULL | auto_increment |
| name | varchar(26) | NO | | NULL | |
| book_id | int | NO | MUL | NULL | |
| comment_count | int | NO | | NULL | |
| is_delete | tinyint(1) | NO | | NULL | |
| pub_date | date | YES | | NULL | |
| read_count | int | NO | | NULL | |
+---------------+-------------+------+-----+---------+----------------+
7 rows in set (0.00 sec)
mysql> select * from bookinfo;
+----+-----------------------+---------+---------------+-----------+----------+------------+
| id | name | book_id | comment_count | is_delete | pub_date | read_count |
+----+-----------------------+---------+---------------+-----------+----------+------------+
| 1 | Python Django开发实战 | 1 | 0 | 0 | NULL | 0 |
| 2 | 编程之美 | 2 | 0 | 0 | NULL | 0 |
| 3 | 西西弗神话 | 3 | 0 | 0 | NULL | 0 |
+----+-----------------------+---------+---------------+-----------+----------+------------+
3 rows in set (0.00 sec)
mysql>
总结
常用查询方法
all()
get()
filter()
他们查询出来的都是对象
first()
last()
order_by()查询出来并且排序
常用模型字段类型
CharField 字符串类型
IntegerField 整型
Boolean 布尔类型
DateField 日期类型