Tuesday, January 21, 2014

Saving models with NOT NULL ForeignKeys referencing each other

Hi,

I just bumped into this issue. Say I have the following models:


class Foo(models.Model):
    bar = models.ForeignKey('Bar', related_name='foos')

class Bar(models.Model):
    default_foo = models.ForeignKey(Foo, related_name='+')


Basically, the idea is that each bar has many foos, but one of them is the bar's default foo. Every foo must have an associated bar, and each bar must have a default foo, so both of the ForeignKey fields are NOT NULL.

This was working great until I realized that now I can't actually create any Foo or Bar objects, because I can't save a Foo object without setting its bar_id, and I can't save a Bar object without setting its foo_id.

Does Django have any kind of way around this, or is the solution just to allow null for one of them (dangerous for data integrity)? Or should I perhaps just not use this kind of circular reference altogether and instead go with something like an is_default field on the Foo model?

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/ca21053a-ac47-4c07-96c1-93294de97cf8%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

No comments:

Post a Comment