你怎么在django模拟这个?

时间:2009-10-20 15:41:02

标签: django django-models uml

考虑类模型如下:

alt text http://www.forteresse.net/site/stackoverflow/classes.png/image

你在models.py中怎么做?

class House(models.Model):
    foo = models.CharField(max_length=123)

class Caravan(models.Model):
    foo = models.CharField(max_length=123)

class Door(models.Model):
    bar = models.CharField(max_length=123)
    house = models.ForeignKey(House)
    caravan = models.ForeignKey(Caravan)

但是这些外键定义可能不是预期的。你如何在django中编码?目的是为“House”和“Caravan”重复使用相同型号的“Door”。

深入挖掘后,我发现了这一点;这是建模问题的正确方法吗?

class House(models.Model):
    foo = models.CharField(max_length=123)

class Caravan(models.Model):
    foo = models.CharField(max_length=123)

class Door(models.Model):
    bar = models.CharField(max_length=123)
    house = models.ForeignKey(House, null=True, blank=True)
    caravan = models.ForeignKey(Caravan, null=True, blank=True)

3 个答案:

答案 0 :(得分:4)

class Door(models.Model):
    bar = models.CharField(max_length=123)

class Caravan(models.Model):
    foo = models.CharField(max_length=123)
    doors = models.ManyToManyField(Door)

class House(models.Model):
    foo = models.CharField(max_length=123)
    doors = models.ManyToManyField(Door)

答案 1 :(得分:2)

我认为你应该尝试:

class Door(models.Model):
    bar = models.CharField(max_length=123)

class House(models.Model):
    foo = models.CharField(max_length=123)
    door = models.ForeignKey(Door)

class Caravan(models.Model):
    foo = models.CharField(max_length=123)
    door = models.ForeignKey(Door)

答案 2 :(得分:1)

您能通过示例查询澄清您真正想要的内容吗?我不清楚。这就是我认为你在寻找的东西:

class Door(models.Model):
  bar = models.CharField(max_length=123)

class House(Door):
  foo = models.CharField(max_length=123)

class Caravan(Door):
  foo = models.CharField(max_length=123)

然后你可以做Caravan.objects.values('foo','bar')

之类的事情