tags:

views:

23

answers:

3

Guys, Is there an easy way to return different fields names from different models by chaining joins? My model:

Class Item(models.Model):
    item_code = models.CharField(max_length=10)
    name = models.CharField(max_length=255)
    ...

Class Stock(models.Model):
    item_code = models.ForeignKey( Item )
    userid = models.ForeignKey( User )
    qty = models.IntegerField()
    ...

I want to select " Item.Item_code, Item.name, Stock.qty where Stock.userid=2 and Item.item_code = Stock.Item_Code"

How do i do this in Django?

Gath

+1  A: 

I want to select " Item.Item_code, Item.name, Stock.qty where Stock.userid=2 and Item.item_code = Stock.Item_Code"

You can pick these specific fields only using one SQL, provided you start from the Stock model. For instance

q = Stock.objects.select_related('userid', 'item_code').filter(
   userid__id = 2).values('item_code__item_code', 'item_code__name', 'qty')

This will help if you want to limit the data and then number of queries. If you are not concerned with this then do:

q = Stock.objects.filter(userid__id = 2)
for stock in q:
    print stock.item_code.item_code
    print stock.item_code.name
    print stock.qty

This will return a queryset with only those fields you have chose using values. You can then iterate through it.

PS: Re: your models.

Class Stock(models.Model):
    item_code = models.ForeignKey( Item )
    userid = models.ForeignKey( User )
    qty = models.IntegerField()
    ...

It is a good idea to use the model name in lower case for FK relationships. For e.g. you ought to write:

Class Stock(models.Model):
    item = models.ForeignKey( Item ) # Changed
    user = models.ForeignKey( User ) # Changed
    qty = models.IntegerField()
    ...
Manoj Govindan
+1  A: 
  1. First of all change fileds names
  2. Read this very carefuly http://docs.djangoproject.com/en/dev/ref/models/querysets/

    Class Item(models.Model):
       item_code = models.CharField(max_length=10)
       name = models.CharField(max_length=255)
       ...
    Class Stock(models.Model):
        item = models.ForeignKey( Item )
        user = models.ForeignKey( User )
        qty = models.IntegerField()
        ...
    
    
    #view 
    stocks = Stock.objects.filter(user=2)
    for stock in stocks:
        print stock.item.item_code, stock.item.name
    #one query version 
    
iddqd
+1  A: 

You can also use this:

Stock.objects.filter(user=2).values('item__item_code', 'item__name')
Dominik Szopa