views:

23

answers:

1

I'm stuggling to get to grips with relationships in ORM.

I want to get a distinct CostItem queryset related to a particular event.

Normally I'd filter CostFixedList for the particular event I'm interested and get a the Cost_Rate id's. From that I could then get the CostItem id's.

I could do this easily in SQL, but can't understand how to start with ORM. Can anyone point me in the right direction?

class Event(models.Model):
    event_type = models.ForeignKey(EventType)
    retailer = models.ForeignKey(Retailer)
    ....

class CostItem(models.Model):
    name = models.CharField("Name", max_length=50, unique=True)
    cost_type = models.ForeignKey(CostType, verbose_name="Type")
    active = models.BooleanField("Active", default=True)

class CostRate(models.Model):
    cost_item = models.ForeignKey(CostItem, verbose_name="Item")
    valid_from = models.DateField("From")
    valid_till = models.DateField("Till")
    unit_amount = models.DecimalField("Price Per Unit", max_digits=5, decimal_places=2)

class CostFixedList(models.Model):
    event = models.ForeignKey(Event)
    cost_rate = models.ForeignKey(CostRate)
    units = models.IntegerField()
    appointment = models.ForeignKey(Appointment, null=True, blank=True)
+1  A: 

I think this should do it (where myevent is the event for which you wish to obtain the CostItem queryset):

qs = CostItem.objects.filter(costrate__costfixedlist__event=myevent)
msanders
Thanks for that. It works!
alj