Django - ManyToManyField是否需要使用ForeignKey?

时间:2013-06-15 00:54:53

标签: django django-models

我继承了遗留数据库,并将其用于Django应用程序。

许多内部表具有一对一,一对多和多对多关系。在直接的SQL应用程序中,数据查询将使用外键来维护参照完整性。在Django中,声明了ManyToManyField方法。

是否必须使用ManyToMany而不是ForeignKey?

1 个答案:

答案 0 :(得分:1)

ForeignKeyManyToMany是两回事。您可能意味着ForeignKey v / s OneToOne

一个例子:

让我们采取一些任意的Developer模型

class Developer(models.Model):
    user = models.OneToOneField(User) #ensure there is a one-to-one relationship between User and Developer model - One user object in django.contrib.auth can be associated with only one Developer and vice versa 
    category = models.ManyToMany(Category) #Developer can be part of many categories, and also one category can be associated with many developers
    birth_address = models.ForeignKey(Address) #He can have only birth place. The address can be associated with many, so it is a `OneToMany` relationship

因此,ManyToMany是多对多关系,ForeignKey是受限制的ManyToMany(多对一关系)。

因此,您可以使用其中任何一个,但如果您希望限制可与相关模型关联的对象数量,则可能最好限制为ForeignKey