我有以下实体:
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之间的关系?
答案 0 :(得分:2)
我认为您想要这样的OneToOneField和ForeignKey:
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)