elG
elG

Reputation: 629

Django 1.8 deep reverse relationship lookup

I have three models:

class Product(models.Model):
    idproduct=models.AutoField(primary_key=True)
    productname=models.CharField(max_length=100, blank=False, null=False)
    product_state=models.BooleanField(default=True)


class ProductInventory(models.Model):
    idinventory=models.AutoField(primary_key=True)
    product_idproduct=models.ForeignKey(Product)
    storage_idstorage=models.ForeignKey(Storage)

class Sale(models.Model):
    idsale=models.AutoField(primary_key=True)
    sale_date = models.DateTimeField(default=timezone.now)
    inventory_idinventory=models.ForeignKey(ProductInventory)

What I want to do is to get all the products that has been sold in this month, I have tried this:

thisdate=datetime.today()
products=Product.objects.filter(product_state=1,productinventory__sale__sale_date__month=thisdate.month).values('pk','productname','productinventory__sale__sale_date')

But first, it gives me "nested lookup is not supported" so I taked off the month filter, but after that it gives me a FieldError: Cannot resolve keyword 'sale' into field

How can I do this?

Upvotes: 0

Views: 152

Answers (2)

Jared Mackey
Jared Mackey

Reputation: 4158

Why are you querying from product? Why wouldn't you query from Sale?

Sale.objects.filter(sale_date__month=thisdate).filter(inventory_idinventory__product_idproduct__productstate=True).values('inventory_idinventory __product_idproduct__pk', 'inventory_idinventory __product_idproduct__ productname')

Also, your naming convention is really bad, I believe Henry H offered a cleanup solution, I would recommend it as well. If you cleaned that up you could make this look really nice with a custom manager method.

Upvotes: 2

Henry H
Henry H

Reputation: 632

class Product(models.Model):
    name=models.CharField(max_length=100, blank=False, null=False)
    state=models.BooleanField(default=True)

class Product_Inventory(models.Model):
    product=models.ForeignKey(Product)
    storage=models.ForeignKey(Storage)

class Sale(models.Model):
    date = models.DateTimeField(default=timezone.now)
    product_inventory=models.ForeignKey(Product_Inventory)

thisdate=datetime.today()
inventory=[]
products=[]

sales = Sale.objects.filter(date__month = thisdate.month)
for item in sales:
    inventory.append(Product_inventory.objects.filter(sale = item))
for product in inventory:
    products.append(Product.objects.filter(product_inventory = product))

print products

Something like this would work. I've taken liberty to clean up your model as it was difficult to read. IDs are automatically added to your models (as pk) so you don't necessarily have to add them here.

Upvotes: 1

Related Questions