本文整理汇总了Python中django.db.models.Model方法的典型用法代码示例。如果您正苦于以下问题:Python models.Model方法的具体用法?Python models.Model怎么用?Python models.Model使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.db.models
的用法示例。
在下文中一共展示了models.Model方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: model_format_dict
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Model [as 别名]
def model_format_dict(obj):
"""
Return a `dict` with keys 'verbose_name' and 'verbose_name_plural',
typically for use with string formatting.
`obj` may be a `Model` instance, `Model` subclass, or `QuerySet` instance.
"""
if isinstance(obj, (models.Model, models.base.ModelBase)):
opts = obj._meta
elif isinstance(obj, models.query.QuerySet):
opts = obj.model._meta
else:
opts = obj
return {
'verbose_name': force_text(opts.verbose_name),
'verbose_name_plural': force_text(opts.verbose_name_plural)
}
示例2: model_ngettext
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Model [as 别名]
def model_ngettext(obj, n=None):
"""
Return the appropriate `verbose_name` or `verbose_name_plural` value for
`obj` depending on the count `n`.
`obj` may be a `Model` instance, `Model` subclass, or `QuerySet` instance.
If `obj` is a `QuerySet` instance, `n` is optional and the length of the
`QuerySet` is used.
"""
if isinstance(obj, models.query.QuerySet):
if n is None:
n = obj.count()
obj = obj.model
d = model_format_dict(obj)
singular, plural = d["verbose_name"], d["verbose_name_plural"]
return ungettext(singular, plural, n or 0)
示例3: define_projection_record_class
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Model [as 别名]
def define_projection_record_class(self):
class ProjectionRecord(models.Model):
uid = models.BigAutoField(primary_key=True)
# Sequence ID (e.g. an entity or aggregate ID).
projection_id = models.UUIDField()
# State of the item (serialized dict, possibly encrypted).
state = models.TextField()
class Meta:
db_table = "projections"
app_label = "projections"
managed = False
self.projection_record_class = ProjectionRecord
示例4: serializer
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Model [as 别名]
def serializer(self, time_format='timestamp', deep=False):
# print self._meta.fields
attr_list = [f.name for f in self._meta.fields]
dic_list = {}
if time_format == 'timestamp':
date_func = datetime_to_timestamp
elif time_format == 'utc':
date_func = datetime_to_utc_string
else:
date_func = datetime_to_string
# print attr_list
for itm in attr_list:
if isinstance(getattr(self, itm), models.Model):
if deep:
dic_list[itm] = getattr(self, itm).serializer(time_format, deep)
elif isinstance(getattr(self, itm), datetime.datetime):
dic_list[itm] = date_func(getattr(self, itm))
else:
dic_list[itm] = getattr(self, itm)
return dic_list
示例5: deconstruct
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Model [as 别名]
def deconstruct(self):
kwargs = {
'name': self.name,
'fields': self.fields,
}
if self.options:
kwargs['options'] = self.options
if self.bases and self.bases != (models.Model,):
kwargs['bases'] = self.bases
if self.managers and self.managers != [('objects', models.Manager())]:
kwargs['managers'] = self.managers
return (
self.__class__.__name__,
[],
kwargs
)
示例6: validate_inlines
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Model [as 别名]
def validate_inlines(self, cls, model):
" Validate inline model admin classes. "
from django.contrib.admin.options import BaseModelAdmin
if hasattr(cls, 'inlines'):
check_isseq(cls, 'inlines', cls.inlines)
for idx, inline in enumerate(cls.inlines):
if not issubclass(inline, BaseModelAdmin):
raise ImproperlyConfigured("'%s.inlines[%d]' does not inherit "
"from BaseModelAdmin." % (cls.__name__, idx))
if not inline.model:
raise ImproperlyConfigured("'model' is a required attribute "
"of '%s.inlines[%d]'." % (cls.__name__, idx))
if not issubclass(inline.model, models.Model):
raise ImproperlyConfigured("'%s.inlines[%d].model' does not "
"inherit from models.Model." % (cls.__name__, idx))
inline.validate(inline.model)
self.check_inline(inline, model)
示例7: test_missing_fields
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Model [as 别名]
def test_missing_fields(self):
class Model(models.Model):
location = OSMField()
checks = []
field = Model._meta.get_field("location")
expected = [
Error(
"The OSMField 'location' references the non-existent latitude "
"field 'location_lat'.",
hint=None,
obj=field,
id="osm_field.E001",
),
Error(
"The OSMField 'location' references the non-existent longitude "
"field 'location_lon'.",
hint=None,
obj=field,
id="osm_field.E002",
),
]
checks.extend(field.check())
self.assertEqual(checks, expected)
示例8: test_missing_fields_exclicitly_given
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Model [as 别名]
def test_missing_fields_exclicitly_given(self):
class Model(models.Model):
location = OSMField(lat_field="lat", lon_field="lon")
checks = []
field = Model._meta.get_field("location")
expected = [
Error(
"The OSMField 'location' references the non-existent latitude "
"field 'lat'.",
hint=None,
obj=field,
id="osm_field.E001",
),
Error(
"The OSMField 'location' references the non-existent longitude "
"field 'lon'.",
hint=None,
obj=field,
id="osm_field.E002",
),
]
checks.extend(field.check())
self.assertEqual(checks, expected)
示例9: register
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Model [as 别名]
def register(self, model, include_fields=[], exclude_fields=[]):
"""
Register a model with actionslog. Actionslog will then track mutations on this model's instances.
:param model: The model to register.
:type model: Model
:param include_fields: The fields to include. Implicitly excludes all other fields.
:type include_fields: list
:param exclude_fields: The fields to exclude. Overrides the fields to include.
:type exclude_fields: list
"""
if issubclass(model, Model):
self._registry[model] = {
'include_fields': include_fields,
'exclude_fields': exclude_fields,
}
self._connect_signals(model)
else:
raise TypeError("Supplied model is not a valid model.")
示例10: setUp
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Model [as 别名]
def setUp(self):
class Meta:
permissions = (
("copy_apptestmodel3", "Can copy apptestmodel3"),
)
attrs_1 = {
'__module__': 'tests.test_app.models',
}
attrs_2 = {
'__module__': 'tests.test_app.models',
'Meta': Meta,
}
self.appconfig = apps.get_app_config('test_app')
self.model1 = type(str('AppTestModel1'), (models.Model, ),
attrs_1.copy())
self.model2 = type(str('AppTestModel2'), (models.Model, ),
attrs_1.copy())
self.model3 = type(str('AppTestModel3'), (models.Model, ),
attrs_2.copy())
示例11: deconstruct
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Model [as 别名]
def deconstruct(self):
kwargs = {
'name': self.name,
'fields': self.fields,
}
if self.options:
kwargs['options'] = self.options
if self.bases and self.bases != (models.Model,):
kwargs['bases'] = self.bases
if self.managers and self.managers != [('objects', models.Manager())]:
kwargs['managers'] = self.managers
return (
self.__class__.__qualname__,
[],
kwargs
)
示例12: references_model
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Model [as 别名]
def references_model(self, name, app_label=None):
name_lower = name.lower()
if name_lower == self.name_lower:
return True
# Check we didn't inherit from the model
models_to_check = [
base for base in self.bases
if base is not models.Model and isinstance(base, (models.base.ModelBase, str))
]
# Check we have no FKs/M2Ms with it
for fname, field in self.fields:
if field.remote_field:
models_to_check.append(field.remote_field.model)
# Now go over all the models and check against them
for model in models_to_check:
model_app_label, model_name = self.model_to_key(model)
if model_name.lower() == name_lower:
if app_label is None or not model_app_label or model_app_label == app_label:
return True
return False
示例13: _get_related_models
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Model [as 别名]
def _get_related_models(m):
"""Return all models that have a direct relationship to the given model."""
related_models = [
subclass for subclass in m.__subclasses__()
if issubclass(subclass, models.Model)
]
related_fields_models = set()
for f in m._meta.get_fields(include_parents=True, include_hidden=True):
if f.is_relation and f.related_model is not None and not isinstance(f.related_model, str):
related_fields_models.add(f.model)
related_models.append(f.related_model)
# Reverse accessors of foreign keys to proxy models are attached to their
# concrete proxied model.
opts = m._meta
if opts.proxy and m in related_fields_models:
related_models.append(opts.concrete_model)
return related_models
示例14: render
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Model [as 别名]
def render(self, apps):
"""Create a Model object from our current state into the given apps."""
# First, make a Meta object
meta_contents = {'app_label': self.app_label, "apps": apps}
meta_contents.update(self.options)
meta = type("Meta", (), meta_contents)
# Then, work out our bases
try:
bases = tuple(
(apps.get_model(base) if isinstance(base, str) else base)
for base in self.bases
)
except LookupError:
raise InvalidBasesError("Cannot resolve one or more bases from %r" % (self.bases,))
# Turn fields into a dict for the body, add other bits
body = {name: field.clone() for name, field in self.fields}
body['Meta'] = meta
body['__module__'] = "__fake__"
# Restore managers
body.update(self.construct_managers())
# Then, make a Model object (apps.register_model is called in __new__)
return type(self.name, bases, body)
示例15: get_normalized_value
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Model [as 别名]
def get_normalized_value(value, lhs):
from django.db.models import Model
if isinstance(value, Model):
value_list = []
sources = lhs.output_field.get_path_info()[-1].target_fields
for source in sources:
while not isinstance(value, source.model) and source.remote_field:
source = source.remote_field.model._meta.get_field(source.remote_field.field_name)
try:
value_list.append(getattr(value, source.attname))
except AttributeError:
# A case like Restaurant.objects.filter(place=restaurant_instance),
# where place is a OneToOneField and the primary key of Restaurant.
return (value.pk,)
return tuple(value_list)
if not isinstance(value, tuple):
return (value,)
return value