I want to filter models object property in views. For example my model has following structure:
class Systems(models.Model):
name = models.CharField(max_length=250,null=True, blank=True,)
slug = models.SlugField(max_length=200, unique=True,null=True)
@property
def get_price(self):
result = dict()
variants = SysVariant.objects.filter(sys=self)
if variant.sale_price:
result['on_sale'] = True
I have other elements also to be passed so I am using result dict here.
Now, I want to filter the Systems model on views, for example: Systems where on_sale = True, I can get property return on template with:
{{systems.get_price.on_sale}}
Is there any possibility where I will be able to create query-set views with property?
I’m sorry, I’m not following what you’re asking here.
Are you trying to create a filter where the left side of the condition is not a field in the model?
If that’s what you’re looking for, then no.
The ORM creates SQL statements. Those queries are executed by the database, and so only information available in the database may be used in those queries.
Further filtering of the data can be done in your code after the queryset has been retrieved.
If you can be more specific with exactly what you’re trying to do, we might be able to offer other options.
Yes, that’s the dictionary key. Where does the value for it come from?
It’s going to be a whole lot more helpful if you provide a complete description of everything that’s going on here. You’re leaving out a lot of details that is making it difficult to provide any assistance of real value.
I think question is pretty clear and code is elaborating the problem more clearly,
I have variant table for Systems, Systems will have variant. With property I am checking Systems has any variants, if SysVariant table has any variant of Systems product I am defining result dictionary value on_sale as True. I am trying do other a lot of required maths with this so adding this on dictionary.
I hope I am able to elaborate the remaining confusions.
Ok, at this point then I think we can say we’ve answered your original question.
In an expression such as SomeModel.objects.filter(some_field=some_value), some_fieldmust be a field in the model.
Now, this means it can also be a field dynamically created within the query through an annotation.
For example, assuming the standard system User model: User.objects.annotate(new_field=F('first_name')).filter(new_field='Ken')
is a valid query.
So, if you can convert whatever it is you’re doing to determine the value of on_sale into a Subquery that can be built into your query, then you can do this within the database.
Otherwise, that filtering will need to be done within Python.