Reputation: 303
I would like to add some property to my model, which stores quantities of some parts, and then filter and order by this property :
models.py
class MAG_warehouse(models.Model):
id_part=models.OneToOneField(MAG_magazyn)
qty_min=models.IntegerField()
qty=models.IntegerField()
views.py
def view(requst):
alert_qty=1.5 #relative quantity, when part should be bought
parts=MAG_warehouse.objects.all()
for item in parts:
item.rel_qty=float(item.qty)/item.qty_min
if item.rel_qty <=alert_qty:
item.color="red" #for css styling
item.alertflag=1
else:
item.alertflag=0
#What i would
#like to have:
sorted_parts=parts.filter(alertflag__exact=1).order_by('rel_qty')
but unfortunately I have attribute error. Without filtering/ordering I can see item.rel_qty and item.color in template.
How can I filter and order my objects by added attribute?
Upvotes: 1
Views: 98
Reputation: 4236
You can try to use .values()
(actually fetch the values from db) and amend the resulting list with the additional properties.
Upvotes: 0
Reputation: 71
As you told you are getting Attribute error bcoz of filter and order_by, but i think your code is right below is the example. i'm sure the attribute error object is not in your property/ or not in your object instance.i got right output. if you provide the snap of you error, will help in finding your solution.
>>> from .models import Model
>>> instances = Model.objects.all()
>>> sorted_instance = instances.filter(column1__exact=45).order_by('column2')
>>> sorted_d
[<Model: Not Finalized>, <Model: Finalized>, <Model: Orderised>, <Model: unordered>]
>>>
Upvotes: 0
Reputation: 4415
Django's .filter and .order_by are database operations, since you're adding color/rel_qty/alertflag to the objects but they aren't present on the database you can't use them. You'll have to use Python, something like
sorted_parts = sorted([part for part in parts if part.alertflag == 1], key=lambda part: part.relqty)
Although you could write that a couple other ways to be sure.
Upvotes: 1