tags:

views:

51

answers:

1

Hi people,

i am making a history page for a website. The structure of my classes is something like this:

alt text

class Person(models.Model):
    name = models.CharField(max_length=100)
    type = models.CharField(max_length=30)

class History(models.Model):
    date = models.DateField(max_length=100)
    action = models.CharField(max_length=250)
    person = models.ForeignKey(Person)

class Parent(Person):
    #some attributes that are not relevant

class Son(Person)
    parent = models.ForeignKey(Parent)
    #other attributes that are not relevant

its quite simple... i have a Parent that has multiple Sons both can do actions on the website and they are all saved in the History table that has a reference to the Person that executed the action. The history table is something like:

date       | action        | person_id 
----------------------------------------
16-12-2010 | saved profile | 1
16-12-2010 | new child     | 2

for a Parent i need to display all his actions and the action of his sons Using sql it would be:

SELECT * FROM History where person_id=1 
UNION 
SELECT h.* FROM History h JOIN Son s ON s.person_ptr_id=h.person_id WHERE s.parent_id=1 

but i have no idea how to do that using django's ORM. Myabe using two querys? a loop? Do you have any ideas? i'd really appreciate some help.. thanks in advance

BTW: i'm using django 1.1

EDIT: i added the attributes in the classes. These are just examples, my tables have more attributes, but this is how django translate the relations into tables

+1  A: 

I think this is the sql:

p = Parent.objects.get(id=1)
history_qs = History.objects.all()
history_qs = history_qs.filter(Q(person=p)|Q(person__in=Son.objects.filter(parent=p)))

The union is not necesary.

diegueus9
thank you! works fine
pleasedontbelong