Jonathan
Jonathan

Reputation: 3534

Filtering reverse forein key set in django

class item(models.Model):
    name = models.CharField()

class itemTxns(models.Model):
    item = models.ForeignKey(item)
    txnDate = models.DateField()
    txn = models.CharField()

Given an "item" object, how do I find the most recent itemTxn associated with that item?

I know I have access to item.itemTxns_set, but is it possible to query that without explicitly calling another get on the itemTxns class?

Upvotes: 0

Views: 62

Answers (1)

item.itemtxns_set.latest('txnDate')

I'm not sure how you'll get around calling it.

You could make it a property of the item class.

class item(models.Model):
    #....
    @property
    def latest_itemtxns(self):
        return self.itemtxns_set.latest('txndate')

By the way I recommend you capitalize your classes to differentiate between instances, variables, and classes.

Upvotes: 2

Related Questions