Opened 5 years ago

Closed 5 years ago

#31394 closed Bug (invalid)

Impossible to create with an inverse one-to-one relationship.

Reported by: Pascal de Sélys Owned by: nobody
Component: Database layer (models, ORM) Version: 2.2
Severity: Normal Keywords:
Cc: deselys.pascal@… Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description (last modified by Pascal de Sélys)

Hello, I don't know if this is a bug or if it's something wanted. If I create two models .

Work >>>

Application One:


class Foo(models.Model):

   foo_bar = models.IntegerField()

   def save(self, *args, **kwargs):
        created = self._state.adding
        super(Foo, self).save(*args, **kwargs)
        if created:
            self.bar_set.create()
            

Application Two:


class Bar(models.Model):

    foo = models.ForeignKey("app1.Foo", on_delete=CASCADE,primary_key=True)
    foo_bar_2 = models.IntegerField()
          

Not work >>>

Application One:


class Foo(models.Model):

   foo_bar = models.IntegerField()

   def save(self, *args, **kwargs):
        created = self._state.adding
        super(EqoLevel, self).save(*args, **kwargs)
        if created:
            self.bar_set.create()
            

Application Two:


class Bar(models.Model):

    foo = models.OneToOneField("app1.Foo", on_delete=CASCADE)
    foo_bar_2 = models.IntegerField()
          

But if I use a I can't run a one to one creation with an inverse relationship and yet during makemigrations it says (fields.W342) Setting unique=True on a ForeignKey has the same effect as using a OneToOneField. (HINT: ForeignKey(unique=True) is usually better served by a OneToOneField.),

Yes but without this function I can't find it. I can also use a signal but I find it a shame to have to create a signal for the simple creation of a one to one relationship that foreign key can provide.
Thank's

Change History (3)

comment:1 by Pascal de Sélys, 5 years ago

Description: modified (diff)

comment:2 by Pascal de Sélys, 5 years ago

Description: modified (diff)

comment:3 by Mariusz Felisiak, 5 years ago

Resolution: invalid
Status: newclosed
Summary: Impossible to create with an inverse one-to-one relationshipImpossible to create with an inverse one-to-one relationship.

W342 is a warning you can always ignore it. You can also create a Bar() manually, e.g.

if created:
    from app2.models import Bar
    Bar.objects.create(foo=self)

Please use one of support channels if you have any further questions.

Note: See TracTickets for help on using tickets.
Back to Top