Django:不对称的ManyToMany关系

时间:2015-05-12 21:59:32

标签: python django database-design

我是使用django的新手,非常感谢您对以下问题的投入。

存在两种模型,即ABA的实例必须属于B的至少一个实例,而B可以包含从0到无限的任意数量的A个实例。

class A(models.Model):
  name = models.CharField(max_length = 128)
  created_date = models.DateTimeField(auto_now_add = True)
  modified_date = models.DateTimeField(auto_now = True)

class B(models.Model):
  name = models.CharField(max_length = 128)
  created_date = models.DateTimeField(auto_now_add = True)
  modified_date = models.DateTimeField(auto_now = True)
  A_list = models.ManyToManyField(A)

好。我认为,根据我给出的描述,ManyToManyField应该用于两个模型。问题是,根据我的阅读,必须使用blank = false来阻止对null进行A分配(因为必须将A分配给至少一个B B 1}})但A可能没有分配blank = false(因此不应该有ManyToMany语句。任何非对称django关系都可以在{{{}}中实现1}} Model

1 个答案:

答案 0 :(得分:0)

You should place the ManyToManyField in A, with removeChild(tileArray[yIndex][xIndex]); tileArray[yIndex][xIndex] = null; , and null=False (default, you got this right). This way, you can create B instances with no problems, even when there are no existing A instances.

When you create an instance of A, blank=False makes sure the B_list field is required. The blank=False makes sure the database will not allow null=False values.

Your code would become:

NULL

For the difference between class A(models.Model): name = models.CharField(max_length = 128) created_date = models.DateTimeField(auto_now_add = True) modified_date = models.DateTimeField(auto_now = True) B_list = models.ManyToManyField('B') class B(models.Model): name = models.CharField(max_length = 128) created_date = models.DateTimeField(auto_now_add = True) modified_date = models.DateTimeField(auto_now = True) and null in Django, see this post:

differentiate null=True, blank=True in django