ForeignKey field with primary relationship

亡梦爱人 提交于 2019-12-12 03:23:48

问题


I have two tables in my database (django: models in my app) as follows:

class Model1(models.Model):
    name = models.CharField()
    #etc....

class Model2(models.Model):
    link = models.ForeignKey(Model1)

Each Model1 can have many instances of Model2 linked to it, but Model2 can only be linked to one Model1 - a basic one-to-many relationship.

My problem is this: I need each Model1 to have a primary Model2 - that is, one of it's related Model2s needs to somehow be marked as "primary".

These are my thoughts so far: should I do this with

  1. A Boolean field on Model2 that says whether it's primary, and then app-level validation that says only one Model2 per Model1 can have that field set True, or
  2. A ForeignKey field on Model1 called "primary_model2" that links to a Model2 instance, with app-level validation that says only a Model2 that is linked to Model1 can be it's primary

Any ideas?? I'm kind of stumped. Thanks in advance!


回答1:


I would go with a boolean on Model2. It's very easy to do a save override that would set any other instances of Model2 that are related to Model1 as false.



来源:https://stackoverflow.com/questions/8401040/foreignkey-field-with-primary-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!