在 Django 中进行无重复外键引用的设计

发布于 2024-11-16 15:10:38 字数 710 浏览 5 评论 0原文

我想创建一个费用跟踪应用程序,每个用户都可以在其中输入费用并将其分类为自己的类别。这是我使用的模型定义:

from django.db import models
from django.contrib.auth.models import User

class Category(models.Model):
    user = models.ForeignKey(User, related_name="my_categories")
    name = models.CharField(max_length=50)

class Expense(models.Model):
    date = models.DateField()
    amount = models.IntegerField()
    description = models.TextField()
    category = models.ForeignKey(Category)
    user = models.ForeignKey(User)

每个类别都必须与一个用户关联,以便我们可以在输入费用时向每个用户显示他自己的类别以供选择。出于类似的原因,每个费用记录都应该与一个用户相关联。但在费用的定义中,我们有两个对用户模型的引用,一个直接通过“用户”字段,另一个通过具有用户引用的“类别”字段。

我认为像这样的多次引用是一件坏事。有更好的方法来建模吗?我知道我们可以从类别参考中找出用户,但这似乎是一种迂回的方法。

I want to create an expense tracking application, where each user can enter expenses and classify them into his own categories. Here is the model definition that I use:

from django.db import models
from django.contrib.auth.models import User

class Category(models.Model):
    user = models.ForeignKey(User, related_name="my_categories")
    name = models.CharField(max_length=50)

class Expense(models.Model):
    date = models.DateField()
    amount = models.IntegerField()
    description = models.TextField()
    category = models.ForeignKey(Category)
    user = models.ForeignKey(User)

Each category will have to be associated with a user so that we can display each user his own categories to choose while entering the expense. For similar reasons, each expense record should be associated with a user. But in definition of Expense, we are having 2 references to the User models, one directly through 'user' field and another through the 'category' field which has a user reference.

I believe that multiple references like this is a bad thing. Is there a better way to model this? I understand that we can find out the user from the category reference, but it seems a roundabout way of doing it.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

夏至、离别 2024-11-23 15:10:38

尽管您的数据库不是 100% 标准化,但就您而言,我不认为第二个参考是多余的。 “费用”和“类别”都是定义明确的实体,属于用户。如果您稍后想要更改外键以允许空类别或ManyToManyField,您将立即注意到这两个用户字段都是必需的。当该列存在时,用户的查找对于数据库和开发人员来说也更加容易。

Although your db is not 100% normalized, in your case, I do not believe the second reference is redundant. Both 'an expense' and 'a category' are well defined entities, which belong to a user. If you will later want to change your foreign key to allow a null category or to a ManyToManyField, you will notice immediatly that both user fields are required. Lookups by user are also much easier for the db and developer when the column is there.

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