user3240688
user3240688

Reputation: 1327

Django model - Foreign Key as Primary Key

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.

Upvotes: 8

Views: 29511

Answers (3)

devxplorer
devxplorer

Reputation: 637

Looks like there was mistake in Yonsy Solis answer in save method(corrected), try 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()

remark: i cant comment yet, so i decide to create answer

Upvotes: 3

Yonsy Solis
Yonsy Solis

Reputation: 964

  1. If you want an OneToOne relation, then use 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)
  1. 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.

  2. 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()

Upvotes: 20

mishbah
mishbah

Reputation: 5597

Have a look at the AutoOneToOneField in django-annoying

https://github.com/skorokithakis/django-annoying

or answer to this question: Can Django automatically create a related one-to-one model?

Upvotes: 1

Related Questions