具有主关系的ForeignKey字段 [英] ForeignKey field with primary relationship
问题描述
我的数据库中有两个表(django:我的应用程序中的模型),如下所示:
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)
每个Model1可以有很多Model2实例链接到它,但Model2只能链接到一个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.
我的问题是:我需要每个Model1有一个主Model2 - 也就是说,它的一个相关的Model2需要以某种方式标记为主要。
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
- Model2上的一个布尔字段,表示它是否为主要,然后应用级验证,表示每个Model1只有一个Model2可以将该字段设置为True,或
- Model1上的一个ForeignKey字段称为primary_model2,它链接到一个Model2实例,具有应用程序级验证,只有链接到Model1的Model2可以是主要的
任何想法?我有点累了。提前感谢!
Any ideas?? I'm kind of stumped. Thanks in advance!
推荐答案
我会在Model2上使用布尔值。这是很容易做一个保存重写,将任何其他Model2的实例与Model1相关的设置为假。
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.
这篇关于具有主关系的ForeignKey字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!