我有三个班级:
1级与3级有一对多的关系;
第2类与第3类有一对多的关系:
1级和2级无关。
如何为这个数据库建模?
答案 0 :(得分:0)
如果不需要,请将ForeignKey
字段设置为null。可以在clean()
方法中验证。
class A(models.Model):
# ...
pass
class B(models.Model):
# ...
pass
class C(models.Model):
# ...
fkA = models.ForeignKey(A, null=True) # to null if not needed
fkB = models.ForeignKey(B, null=True) # to null if not needed
# ...
def clean(self):
# only one fk allowed
if self.fkA and self.fkB:
raise ValidationError("Relation either to A or to B - not both!")
# one fk required
if not self.fkA and not self.fkB:
raise ValidationError("Relation to A or to B required!")
使用模型继承
class A(models.Model):
# ...
pass
class B(models.Model):
# ...
pass
class AbstractC(models.Model):
# ...
class Meta:
# ...
abstract = True
class CtoA(AbstractC)
# ...
fkA = models.ForeignKey(A)
# ...
class CtoB(AbstractC)
# ...
fkB = models.ForeignKey(B)
# ...
$ python manage.py makemigrations
$ python manage.py migrate