一对一和一对多建模

发布于 2025-01-04 08:11:04 字数 543 浏览 0 评论 0原文

人员和地址也是如此。一个人可以拥有多个地址,但每人只能将一个地址标记为主要地址。以下是我考虑过的两种方法。

第一个在保存时很尴尬,因为我必须先保存该人,然后保存该变体,然后再次使用该变体 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

甜扑 2025-01-11 08:11:04

对于这种情况,我通常会选择选项#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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文