开发者

Define a default child (reverse ForeignKey)

开发者 https://www.devze.com 2023-03-31 19:37 出处:网络
I have 2 models Foo and Bar. Each Foo has multiple Bars, but one needs to be the \"default\". At this point I have a foreignkey in Bar pointing to Foo, but now I need a way to specify which of the Bar

I have 2 models Foo and Bar. Each Foo has multiple Bars, but one needs to be the "default". At this point I have a foreignkey in Bar pointing to Foo, but now I need a way to specify which of the Bar's belonging to Foo is the default. I tried setting another foreignkey in Foo that points to a Bar (with a unique related_name), but I get all sorts of errors (including in the django-admin templates).

Code so far:

class Foo(models.Model):
    default_bar = models.ForeignKey('Bar')

class Bar(models.Model):
    foo = models.ForeignKey(Foo)

I have absolutely NO problem with a completely new solution as I'm probably doing it wrong anyways. The only other way I can think of is to have a separate table that connects Foos and Bars and having the Foo part uniq开发者_C百科ue, but that makes the admin interface a MESS.


If a Foo can have multiple Bars, then can a Bar belong to multiple Foos? If so then you can solve this really easily with a ManyToManyField and the through parameter, like this:

class Foo(models.Model):
    name = models.CharField(max_length=128)
    bars = models.ManyToManyField(Bar, through='FooBar')

class Bar(models.Model):
    name = models.CharField(max_length=128)

class FooBar(models.Model):
    foo = models.ForeignKey(Foo)
    bar = models.ForeignKey(Bar)
    is_default = models.BooleanField()

Check the Django documentation on "Extra fields on many-to-many relationships".

And just as a note, posting a simple version of your actual problem (ie. saying Person and Group vs. Foo and Bar) helps, as we get a better understanding of what you're actually trying to model! That way it's easier to see where the relationships should actually go.

0

精彩评论

暂无评论...
验证码 换一张
取 消