I have the following 2 tables
In models.py
class Foo(models.Model):
uuid = models.CharField(_('UUID'), primary_key=True, default=uuid4)
and
class FooExt(models.Model):
uuid = models.ForeignKey(Foo, verbose_name=_('UUID'), primary_key=True)
time = models.DateTimeField(_('Create DateTime'), auto_now_add=True)
Basically, I have Foo
and FooExt
. I want a one-to-one relation between FooExt
. That's why I set FooExt
's primary key to be foreign key into Foo
(not sure if this is the right thing to do).
Now I add an entry into Foo
. Does an entry for FooExt
automatically get created? Or do I need to manually add an entry to both Foo
and FooExt
?
Is there anything I can do to get the "automatic" add feature? Conceptually, these 2 tables describe the same thing, but I just don't want to pollute Foo
with extra information. So it'd be great if an add to Foo
automatically creates a corresponding FooExt
.
yes it works for me. thanks. just to play the devils advocate, what are the downsides of this method? yeah, you right, you can perform check: if Foo already created, then you dont create any new FooExt , you can do it with if self.pk: in save method, this answer may help.
To define a relationship between two models, you need to define the ForeignKey field in the model from the Many side of the relationship. In other words, ForeignKey should be placed in the Child table, referencing the Parent table.
If you'd like to specify a custom primary key, specify primary_key=True on one of your fields. If Django sees you've explicitly set Field.primary_key , it won't add the automatic id column. Each model requires exactly one field to have primary_key=True (either explicitly declared or automatically added).
models.OneToOneField
instead of models.ForeignKey
. with foreign keys you will need add unique=True
in you ForeignKey:class Foo(models.Model): uuid = models.CharField(_('UUID'), primary_key=True, default=uuid4) class FooExt(models.Model): uuid = models.OneToOneField(Foo, verbose_name=_('UUID'), primary_key=True) time = models.DateTimeField(_('Create DateTime'), auto_now_add=True)
No, an entry for FooExt don't get created when you create a Foo instance, you need to manually add an entry to both Foo and FooExt. think in Places and Restaurants, many places can be restaurants, but no all the places are restaurants.
if you like an automatic add feature inside Foo
that create a FooExt
instance, then you can overload the save
method inside Foo
that create and save FooExt
instance too, something like this:
class Foo(models.Model): .... .... def save(self, *args, **kwargs): super(Foo, self).save(*args, **kwargs) foo_ext = FooExt() foo_ext.uuid = self foo_ext.save()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With