How do you model this in django?
Considering the class model as follows:
alt text http://www.forteresse.net/site/stackoverflow/classes.png/image
How do you do this in models.py?
class House(models.Model):
foo = mod开发者_如何学JAVAels.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)
But these foreign key definitions may not be what is intended. How do you code this in django? The intention is to reuse the same model "Door" for both "House" and "Caravan".
After digging deeper, I found this; is this the right way to model the problem?
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)
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)
I think you should try:
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)
Can you clarify what you're really looking for with an example query? It's not clear to me. This is what I think you're looking for:
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)
Then you can do things like Caravan.objects.values('foo','bar')
精彩评论