问题
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
- 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
- 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