一对一和一对多建模
人员和地址也是如此。一个人可以拥有多个地址,但每人只能将一个地址标记为主要地址。以下是我考虑过的两种方法。
第一个在保存时很尴尬,因为我必须先保存该人,然后保存该变体,然后再次使用该变体 pk 保存该人。
对于第二种方法,防止一个人拥有多个主要地址的唯一方法似乎是在代码中添加验证。
# First approach
class Person(models.Model):
primary_address = models.ForeignKey('Address')
...
class Address(models.Model):
person = models.ForeignKey(Person)
...
# Second approach
class Person(models.Model):
...
class Address(models.Model):
person = models.ForeignKey(Person)
is_primary = models.BooleanField()
...
So have people and addresses. A person may have more then one address but only one address can be marked as primary per person. The following are two ways I have considered doing it.
The first is awkward when saving as I have to save the person then the variant then the person again with the variant pk.
With the second approach it seems like the only way to prevent a person from having more then one primary address is to add validation in code.
# First approach
class Person(models.Model):
primary_address = models.ForeignKey('Address')
...
class Address(models.Model):
person = models.ForeignKey(Person)
...
# Second approach
class Person(models.Model):
...
class Address(models.Model):
person = models.ForeignKey(Person)
is_primary = models.BooleanField()
...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于这种情况,我通常会选择选项#2。查询起来稍微困难一些,因为您有时必须执行额外的查询+过滤器来选择它,但正如您所提到的,它也为您提供了更干净地保存它的选项。
使用选项#2,您可以重写地址模型的保存方法,以便将用户的所有其他地址标记为非主要地址(如果其本身是主要地址)。
I usually choose option #2 for situations like this. It is slightly more difficult to query, in that you sometimes have to do an additional query + a filter to select it, but it also gives you the option to save it more cleanly, as you mentioned.
With option #2, you can override the save method of the address model so that it marks all other addresses from the user as non-primary if itself is primary.