toaster
toaster

Reputation: 165

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

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)

Upvotes: 0

Views: 228

Answers (3)

Adam Nelson
Adam Nelson

Reputation: 8090

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

Upvotes: 1

nabucosound
nabucosound

Reputation: 1293

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)

Upvotes: 4

Aurelio Martin Massoni
Aurelio Martin Massoni

Reputation: 1706

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)

Upvotes: 2

Related Questions