0

I am using version 1.8

class ProductProduct(models.Model):
    product_tmpl = models.ForeignKey(ProductTemplateModel)
    default_code = models.CharField()
    name_template = models.CharField()
    ...

class PurchaseOrder(models.Model):
    # fields...

class PurchaseOrderLine(models.Model):
    id = models.IntegerField()
    product_id = models.ForeignKey(ProductProduct)
    order_id = models.ForeignKey(PurchaseOrder)

I only need to list the PurchaseOrder records which default_code (in ProductProduct model) is null.

I cannot filter using "purchaseorderline_set.product_id_set.default_code=None" since purchaseorderline_set is a query set and it does not have an attribute product_id_set as indicated here. So I tried using this:

orders_recs = PurchaseOrder.objects.all().order_by('-id')
orders_recs = PurchaseOrder.objects.filter(purchaseorderline_set.product_id_set.default_code=None).order_by('-id')
orders = []
for order_rec in orders_recs:
    line = order_rec.purchaseorderline_set.all()
    if line and line[0].product_id.default_code == None:
        orders.append(order_rec)

But it's taking over 3 secs. I consider this A LOT taking in consideration that I am only one working in my DEV env (machine is NOT slow) and DB is really small so far, since there are only 269 PurchaseOrder recs, 396 PurchaseOrderLine recs and 726 ProductProduct recs.

I suppose there is an efficient way that I am not seeing.

Rmartin
  • 243
  • 3
  • 6
  • 14

2 Answers2

0

Sorry if it don't help you

# pp:ProductProduct
# po:PurchaseOrder
# pol:PurchaseOrderLine
# List PP with None
pp = PP.objects.filter(def_c = None)
# list pol have pp None
pol = POL.objects.filter(prod__in = pp)
# create a list ids of POL
ids = []
for i in pol: 
    ids.append(pol.order_id)
po = PO.objects.filter(id__in = ids)
Exprator
  • 26,992
  • 6
  • 47
  • 59
Nam Nguyễn
  • 552
  • 4
  • 20
  • 1
    hi @Nam Nguyễn, I think pol_ids = POL.objects.filter(prod__in = pp).values_list('id', flat=True) – khue bui May 31 '17 at 06:32
  • yes, create a list of id in query is better. i just show an other way to query, don't need to do the complicate thing like above – Nam Nguyễn May 31 '17 at 07:13
  • I just ended up using the method with "values_list('id', flat=True)". Now it's much faster! Thanks – Rmartin May 31 '17 at 22:18
0

Take a look at conditional expressions

Kritz
  • 7,099
  • 12
  • 43
  • 73