ForeignKey或ManyToMany - 何时使用?我想知道哪个版本更好。 InvoiceHistory
模型将存储Invoice
REJECTED = 1
SUBMITTED = 2
APPROVED = 3
HISTORY_CHOICES = (
REJECTED, "Rejected",
SUBMITTED, "Submitted",
APPROVED, "Approved",
)
class InvoiceHistory(TimeStampedModel)
user = models.ForeignKey(settings.AUTH_USER_MODEL)
action = models.IntegerField(choices=HISTORY_CHOICES)
class Invoice(models.Model):
number = models.CharField(...)
history = models.ManyToManyField(InvoiceHistory)
或使用ForeignKey的版本:
class Invoice(models.Model):
number = models.CharField(...)
class InvoiceHistory(TimeStampedModel)
user = models.ForeignKey(settings.AUTH_USER_MODEL)
action = models.IntegerField(choices=HISTORY_CHOICES)
invoice = models.ForeignKey(Invoice)
答案 0 :(得分:1)
这不是“哪个更好”的问题,而是“哪一个正确模拟你的领域”的问题。在第一个示例中,Invoice和InvoiceHistory之间存在多对多的关系,这意味着同一个InvoiceHistory实例可以属于许多Invoice实例。我没有你的项目的完整背景,但我不确定它在这里有意义......