Django模型来建模“具有”和“包含”关系

时间:2018-07-26 10:15:07

标签: django django-models

我有以下实体:

from django.db import models

class Foo(models.Model):
    pass

class Bar(models.Model):
    pass


class FooBar(models.Model):
    pwned_foo = # Foobar contains one Foo object
    bars = # Collection of Bar objects

如何在FooBar类中表达Foo,Bar和FooBar之间的关系?

2 个答案:

答案 0 :(得分:2)

我认为您想要这样的OneToOneFieldForeignKey

from django.db import models

class Foo(models.Model):
    pass

class Bar(models.Model):
    foobar = models.ForeignKey(FooBar, related_name='bars')


class FooBar(models.Model):
    pwned_foo = models.OneToOneField(Foo)
    bars = # Collection of Bar objects
    # you can access bars via the reverse relationship like
    # myfoobar.bars

这假设您想要与条形图建立1-N关系。如果要建立N-N关系,请使用ManyToManyField

如果您确实需要保持Bar的任何关系清洁(您能解释原因吗?),您可以尝试使用ArrayField之类的警告,该警告仅适用于postgresql,并且您需要查询集中的重新实现关系等...我怀疑性能也会受到影响...

答案 1 :(得分:1)

from django.db import models

class Foo(models.Model):
    pass

class Bar(models.Model):
   pass


class FooBar(models.Model):
    pwned_foo = models.OneToOneField(Foo, on_delete=models.CASCADE)
    bars = models.ForeignKey(Bar, on_delete=models.CASCADE)