Python django.db.models.OneToOneField() Examples

The following are 30 code examples for showing how to use django.db.models.OneToOneField(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.db.models , or try the search function .

Example 1
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
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) 
Example 2
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
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")
        ) 
Example 3
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
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) 
Example 4
Project: dvhb-hybrid   Author: dvhb   File: convert.py    License: MIT License 6 votes vote down vote up
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) 
Example 5
Project: StormOnline   Author: stormsha   File: xversion.py    License: Apache License 2.0 5 votes vote down vote up
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) 
Example 6
Project: GTDWeb   Author: lanbing510   File: models.py    License: GNU General Public License v2.0 5 votes vote down vote up
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) 
Example 7
Project: dingtalk-django-example   Author: 007gzs   File: model.py    License: GNU General Public License v3.0 5 votes vote down vote up
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) 
Example 8
Project: django-seed   Author: Brobin   File: seeder.py    License: MIT License 5 votes vote down vote up
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 
Example 9
Project: jet-bridge   Author: jet-admin   File: configuration.py    License: MIT License 5 votes vote down vote up
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))) 
Example 10
Project: meeting   Author: 007gzs   File: utils.py    License: GNU General Public License v3.0 5 votes vote down vote up
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) 
Example 11
Project: weibo-analysis-system   Author: Superbsco   File: xversion.py    License: MIT License 5 votes vote down vote up
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) 
Example 12
Project: myblog   Author: myminwang   File: xversion.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
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) 
Example 13
Project: CTF_AWD_Platform   Author: xuchaoa   File: xversion.py    License: MIT License 5 votes vote down vote up
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) 
Example 14
Project: django_OA   Author: abaoMAO   File: xversion.py    License: GNU General Public License v3.0 5 votes vote down vote up
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) 
Example 15
Project: graphene-django-extras   Author: eamigo86   File: converter.py    License: MIT License 5 votes vote down vote up
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) 
Example 16
Project: wagtailstreamforms   Author: labd   File: test_form_settings.py    License: MIT License 5 votes vote down vote up
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") 
Example 17
Project: luscan-devel   Author: blackye   File: models.py    License: GNU General Public License v2.0 5 votes vote down vote up
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) 
Example 18
Project: Mxonline3   Author: mtianyan   File: xversion.py    License: Apache License 2.0 5 votes vote down vote up
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) 
Example 19
Project: imoocc   Author: iopsgroup   File: xversion.py    License: GNU General Public License v2.0 5 votes vote down vote up
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) 
Example 20
Project: devops   Author: madre   File: xversion.py    License: MIT License 5 votes vote down vote up
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) 
Example 21
Project: django-sqlserver   Author: denisenkom   File: test_operations.py    License: MIT License 5 votes vote down vote up
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") 
Example 22
Project: django-sqlserver   Author: denisenkom   File: models.py    License: MIT License 5 votes vote down vote up
def __str__(self):
        return self.title


# order_with_respect_to points to a model with a OneToOneField primary key. 
Example 23
Project: online   Author: myminwang   File: xversion.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
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) 
Example 24
Project: django-seal   Author: charettes   File: test_models.py    License: MIT License 5 votes vote down vote up
def test_make_non_sealable_model_subclass(self):
        class Foo(models.Model):
            pass

        class Bar(models.Model):
            foo = models.BooleanField(default=False)
            fk = models.ForeignKey(Foo, models.CASCADE, related_name='fk_bar')
            o2o = models.OneToOneField(Foo, models.CASCADE, related_name='o2o_bar')
            m2m = models.ManyToManyField(Foo, related_name='m2m_bar')

        make_model_sealable(Bar)

        # Forward fields descriptors should have been made sealable.
        self.assertIsInstance(Bar.foo, SealableDeferredAttribute)
        self.assertIsInstance(Bar.fk, SealableForwardManyToOneDescriptor)
        self.assertIsInstance(Bar.o2o, SealableForwardOneToOneDescriptor)
        self.assertIsInstance(Bar.m2m, SealableManyToManyDescriptor)

        # But not the remote fields.
        self.assertNotIsInstance(Foo.fk_bar, SealableReverseManyToOneDescriptor)
        self.assertNotIsInstance(Foo.o2o_bar, SealableReverseOneToOneDescriptor)
        self.assertNotIsInstance(Foo.m2m_bar, SealableManyToManyDescriptor)

        # Should seal local related objects.
        make_model_sealable(Foo)
        self.assertIsInstance(Foo.fk_bar, SealableReverseManyToOneDescriptor)
        self.assertIsInstance(Foo.o2o_bar, SealableReverseOneToOneDescriptor)
        self.assertIsInstance(Foo.m2m_bar, SealableManyToManyDescriptor) 
Example 25
Project: Dailyfresh-B2C   Author: BeanWei   File: xversion.py    License: Apache License 2.0 5 votes vote down vote up
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) 
Example 26
Project: djongo   Author: nesdis   File: test_models.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_missing_parent_link(self):
        msg = 'Add parent_link=True to invalid_models_tests.ParkingLot.parent.'
        with self.assertRaisesMessage(ImproperlyConfigured, msg):
            class Place(models.Model):
                pass

            class ParkingLot(Place):
                parent = models.OneToOneField(Place, models.CASCADE) 
Example 27
Project: djongo   Author: nesdis   File: test_operations.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
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") 
Example 28
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_abstract_parent_link(self):
        class A(models.Model):
            pass

        class B(A):
            a = models.OneToOneField('A', parent_link=True, on_delete=models.CASCADE)

            class Meta:
                abstract = True

        class C(B):
            pass

        self.assertIs(C._meta.parents[A], C._meta.get_field('a')) 
Example 29
Project: djongo   Author: nesdis   File: test_models.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_missing_parent_link(self):
        msg = 'Add parent_link=True to invalid_models_tests.ParkingLot.parent.'
        with self.assertRaisesMessage(ImproperlyConfigured, msg):
            class Place(models.Model):
                pass

            class ParkingLot(Place):
                parent = models.OneToOneField(Place, models.CASCADE) 
Example 30
Project: djongo   Author: nesdis   File: test_operations.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
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")