2009-10-20 42 views
0

考慮到類模型如下:你如何在django中建模?

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」重複使用相同的模型「門」。

經過深入挖掘,我發現這個;這是模擬問題的正確方法嗎?

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) 

回答

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) 
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) 
+0

有可能是在一所房子或在大篷車多門...... – toaster

+3

所以使用ManyToManyField。 –

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')