本文整理汇总了Python中django.db.models.OneToOneField方法的典型用法代码示例。如果您正苦于以下问题:Python models.OneToOneField方法的具体用法?Python models.OneToOneField怎么用?Python models.OneToOneField使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.db.models
的用法示例。
在下文中一共展示了models.OneToOneField方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_lookup_allowed_onetoone
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import OneToOneField [as 别名]
def test_lookup_allowed_onetoone(self):
class Department(models.Model):
code = models.CharField(max_length=4, unique=True)
class Employee(models.Model):
department = models.ForeignKey(Department, models.CASCADE, to_field="code")
class EmployeeProfile(models.Model):
employee = models.OneToOneField(Employee, models.CASCADE)
class EmployeeInfo(models.Model):
employee = models.OneToOneField(Employee, models.CASCADE)
description = models.CharField(max_length=100)
class EmployeeProfileAdmin(ModelAdmin):
list_filter = [
'employee__employeeinfo__description',
'employee__department__code',
]
ma = EmployeeProfileAdmin(EmployeeProfile, self.site)
# Reverse OneToOneField
self.assertIs(ma.lookup_allowed('employee__employeeinfo__description', 'test_value'), True)
# OneToOneField and ForeignKey
self.assertIs(ma.lookup_allowed('employee__department__code', 'test_value'), True)
示例2: test_parent_child_one_to_one_link
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import OneToOneField [as 别名]
def test_parent_child_one_to_one_link(self):
# Since the parent and child are linked by an automatically created
# OneToOneField, you can get from the parent to the child by using the
# child's name.
self.assertEqual(
Place.objects.get(name="Demon Dogs").restaurant,
Restaurant.objects.get(name="Demon Dogs")
)
self.assertEqual(
Place.objects.get(name="Ristorante Miron").restaurant.italianrestaurant,
ItalianRestaurant.objects.get(name="Ristorante Miron")
)
self.assertEqual(
Restaurant.objects.get(name="Ristorante Miron").italianrestaurant,
ItalianRestaurant.objects.get(name="Ristorante Miron")
)
示例3: convert
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import OneToOneField [as 别名]
def convert(self, dj_field):
result = []
if isinstance(dj_field, (ForeignKey, OneToOneField)):
result.append(dj_field.column)
convert_from = dj_field.target_field
else:
result.append(dj_field.name)
convert_from = dj_field
internal_type = convert_from.get_internal_type()
convert_to = self._types.get(internal_type)
if convert_to is not None:
result.append(self._convert_type(convert_from, convert_to))
else:
logger.info(
'Not found corresponding '
'SQLAlchemy type for "%s"(%r)',
internal_type,
dj_field
)
return sa.column(*result)
示例4: _register_model
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import OneToOneField [as 别名]
def _register_model(admin, model):
if not hasattr(admin, 'reversion_format'):
admin.reversion_format = 'json'
if not is_registered(model):
inline_fields = []
for inline in getattr(admin, 'inlines', []):
inline_model = inline.model
if getattr(inline, 'generic_inline', False):
ct_field = getattr(inline, 'ct_field', 'content_type')
ct_fk_field = getattr(inline, 'ct_fk_field', 'object_id')
for field in model._meta.many_to_many:
if isinstance(field, GenericRelation) \
and field.rel.to == inline_model \
and field.object_id_field_name == ct_fk_field \
and field.content_type_field_name == ct_field:
inline_fields.append(field.name)
_autoregister(admin, inline_model)
else:
fk_name = getattr(inline, 'fk_name', None)
if not fk_name:
for field in inline_model._meta.fields:
if isinstance(field, (models.ForeignKey, models.OneToOneField)) and issubclass(model, field.rel.to):
fk_name = field.name
_autoregister(admin, inline_model, follow=[fk_name])
if not inline_model._meta.get_field(fk_name).rel.is_hidden():
accessor = inline_model._meta.get_field(fk_name).remote_field.get_accessor_name()
inline_fields.append(accessor)
_autoregister(admin, model, inline_fields)
示例5: add_fields
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import OneToOneField [as 别名]
def add_fields(self, form, index):
"""Add a hidden field for the object's primary key."""
from django.db.models import AutoField, OneToOneField, ForeignKey
self._pk_field = pk = self.model._meta.pk
# If a pk isn't editable, then it won't be on the form, so we need to
# add it here so we can tell which object is which when we get the
# data back. Generally, pk.editable should be false, but for some
# reason, auto_created pk fields and AutoField's editable attribute is
# True, so check for that as well.
def pk_is_not_editable(pk):
return ((not pk.editable) or (pk.auto_created or isinstance(pk, AutoField))
or (pk.rel and pk.rel.parent_link and pk_is_not_editable(pk.rel.to._meta.pk)))
if pk_is_not_editable(pk) or pk.name not in form.fields:
if form.is_bound:
# If we're adding the related instance, ignore its primary key
# as it could be an auto-generated default which isn't actually
# in the database.
pk_value = None if form.instance._state.adding else form.instance.pk
else:
try:
if index is not None:
pk_value = self.get_queryset()[index].pk
else:
pk_value = None
except IndexError:
pk_value = None
if isinstance(pk, OneToOneField) or isinstance(pk, ForeignKey):
qs = pk.rel.to._default_manager.get_queryset()
else:
qs = self.model._default_manager.get_queryset()
qs = qs.using(form.instance._state.db)
if form._meta.widgets:
widget = form._meta.widgets.get(self._pk_field.name, HiddenInput)
else:
widget = HiddenInput
form.fields[self._pk_field.name] = ModelChoiceField(qs, initial=pk_value, required=False, widget=widget)
super(BaseModelFormSet, self).add_fields(form, index)
示例6: __init__
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import OneToOneField [as 别名]
def __init__(self, to, on_delete=models.DO_NOTHING, to_field=None, db_constraint=False, **kwargs):
super(OneToOneField, self).__init__(to, on_delete, to_field, db_constraint=db_constraint, **kwargs)
示例7: guess_field_formatters
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import OneToOneField [as 别名]
def guess_field_formatters(self, faker):
"""
Gets the formatter methods for each field using the guessers
or related object fields
:param faker: Faker factory object
"""
formatters = {}
name_guesser = NameGuesser(faker)
field_type_guesser = FieldTypeGuesser(faker)
for field in self.model._meta.fields:
field_name = field.name
if field.primary_key:
continue
if field.get_default():
formatters[field_name] = field.get_default()
continue
if isinstance(field, (ForeignKey, ManyToManyField, OneToOneField)):
formatters[field_name] = self.build_relation(field, field.related_model)
continue
if not field.choices:
formatter = name_guesser.guess_format(field_name)
if formatter:
formatters[field_name] = formatter
continue
formatter = field_type_guesser.guess_format(field)
if formatter:
formatters[field_name] = formatter
continue
return formatters
示例8: get_related_models
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import OneToOneField [as 别名]
def get_related_models(self, model):
fields = model._meta.get_fields(include_hidden=True)
def filter_fields(x):
if any(map(lambda rel: isinstance(x, rel), [
models.OneToOneRel,
models.OneToOneField,
models.ManyToOneRel,
models.ManyToManyField,
models.ManyToManyRel
])):
return True
return False
return list(map(lambda x: x.related_model, filter(filter_fields, fields)))
示例9: _register_model
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import OneToOneField [as 别名]
def _register_model(admin, model):
if not hasattr(admin, 'reversion_format'):
admin.reversion_format = 'json'
if not is_registered(model):
inline_fields = []
for inline in getattr(admin, 'inlines', []):
inline_model = inline.model
if getattr(inline, 'generic_inline', False):
ct_field = getattr(inline, 'ct_field', 'content_type')
ct_fk_field = getattr(inline, 'ct_fk_field', 'object_id')
for field in model._meta.many_to_many:
if isinstance(field, GenericRelation) \
and field.rel.to == inline_model \
and field.object_id_field_name == ct_fk_field \
and field.content_type_field_name == ct_field:
inline_fields.append(field.name)
_autoregister(admin, inline_model)
else:
fk_name = getattr(inline, 'fk_name', None)
if not fk_name:
for field in inline_model._meta.fields:
if isinstance(field, (models.ForeignKey, models.OneToOneField)) and issubclass(model, field.remote_field.model):
fk_name = field.name
_autoregister(admin, inline_model, follow=[fk_name])
if not inline_model._meta.get_field(fk_name).remote_field.is_hidden():
accessor = inline_model._meta.get_field(fk_name).remote_field.get_accessor_name()
inline_fields.append(accessor)
_autoregister(admin, model, inline_fields)
示例10: convert_field_to_djangomodel
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import OneToOneField [as 别名]
def convert_field_to_djangomodel(
field, registry=None, input_flag=None, nested_field=False
):
model = get_related_model(field)
def dynamic_type():
# Avoid create field for auto generate OneToOneField product of an inheritance
if isinstance(field, models.OneToOneField) and issubclass(
field.model, field.related_model
):
return
if input_flag and not nested_field:
return ID(
description=field.help_text or field.verbose_name,
required=is_required(field) and input_flag == "create",
)
_type = registry.get_type_for_model(model, for_input=input_flag)
if not _type:
return
return Field(
_type,
description=field.help_text or field.verbose_name,
required=is_required(field) and input_flag == "create",
)
return Dynamic(dynamic_type)
示例11: test_form
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import OneToOneField [as 别名]
def test_form(self):
field = self.get_field(AbstractFormSetting, "form")
self.assertModelField(field, models.OneToOneField)
self.assertEqual(field.remote_field.model, "wagtailstreamforms.Form")
self.assertEqual(field.remote_field.on_delete, models.CASCADE)
self.assertEqual(field.remote_field.related_name, "advanced_settings")
示例12: add_fields
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import OneToOneField [as 别名]
def add_fields(self, form, index):
"""Add a hidden field for the object's primary key."""
from django.db.models import AutoField, OneToOneField, ForeignKey
self._pk_field = pk = self.model._meta.pk
# If a pk isn't editable, then it won't be on the form, so we need to
# add it here so we can tell which object is which when we get the
# data back. Generally, pk.editable should be false, but for some
# reason, auto_created pk fields and AutoField's editable attribute is
# True, so check for that as well.
def pk_is_not_editable(pk):
return ((not pk.editable) or (pk.auto_created or isinstance(pk, AutoField))
or (pk.rel and pk.rel.parent_link and pk_is_not_editable(pk.rel.to._meta.pk)))
if pk_is_not_editable(pk) or pk.name not in form.fields:
if form.is_bound:
pk_value = form.instance.pk
else:
try:
if index is not None:
pk_value = self.get_queryset()[index].pk
else:
pk_value = None
except IndexError:
pk_value = None
if isinstance(pk, OneToOneField) or isinstance(pk, ForeignKey):
qs = pk.rel.to._default_manager.get_query_set()
else:
qs = self.model._default_manager.get_query_set()
qs = qs.using(form.instance._state.db)
form.fields[self._pk_field.name] = ModelChoiceField(qs, initial=pk_value, required=False, widget=HiddenInput)
super(BaseModelFormSet, self).add_fields(form, index)
示例13: _register_model
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import OneToOneField [as 别名]
def _register_model(admin, model):
if not hasattr(admin, 'revision_manager'):
admin.revision_manager = default_revision_manager
if not hasattr(admin, 'reversion_format'):
admin.reversion_format = 'json'
if not admin.revision_manager.is_registered(model):
inline_fields = []
for inline in getattr(admin, 'inlines', []):
inline_model = inline.model
if getattr(inline, 'generic_inline', False):
ct_field = getattr(inline, 'ct_field', 'content_type')
ct_fk_field = getattr(inline, 'ct_fk_field', 'object_id')
for field in model._meta.many_to_many:
if isinstance(field, GenericRelation) and field.rel.to == inline_model and field.object_id_field_name == ct_fk_field and field.content_type_field_name == ct_field:
inline_fields.append(field.name)
_autoregister(admin, inline_model)
else:
fk_name = getattr(inline, 'fk_name', None)
if not fk_name:
for field in inline_model._meta.fields:
if isinstance(field, (models.ForeignKey, models.OneToOneField)) and issubclass(model, field.rel.to):
fk_name = field.name
_autoregister(admin, inline_model, follow=[fk_name])
if not inline_model._meta.get_field(fk_name).rel.is_hidden():
accessor = inline_model._meta.get_field(
fk_name).related.get_accessor_name()
inline_fields.append(accessor)
_autoregister(admin, model, inline_fields)
示例14: test_create_model_inheritance
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import OneToOneField [as 别名]
def test_create_model_inheritance(self):
"""
Tests the CreateModel operation on a multi-table inheritance setup.
"""
project_state = self.set_up_test_model("test_crmoih")
# Test the state alteration
operation = migrations.CreateModel(
"ShetlandPony",
[
('pony_ptr', models.OneToOneField(
'test_crmoih.Pony',
models.CASCADE,
auto_created=True,
primary_key=True,
to_field='id',
serialize=False,
)),
("cuteness", models.IntegerField(default=1)),
],
)
new_state = project_state.clone()
operation.state_forwards("test_crmoih", new_state)
self.assertIn(("test_crmoih", "shetlandpony"), new_state.models)
# Test the database alteration
self.assertTableNotExists("test_crmoih_shetlandpony")
with connection.schema_editor() as editor:
operation.database_forwards("test_crmoih", editor, project_state, new_state)
self.assertTableExists("test_crmoih_shetlandpony")
# And test reversal
with connection.schema_editor() as editor:
operation.database_backwards("test_crmoih", editor, new_state, project_state)
self.assertTableNotExists("test_crmoih_shetlandpony")
示例15: __str__
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import OneToOneField [as 别名]
def __str__(self):
return self.title
# order_with_respect_to points to a model with a OneToOneField primary key.