Order Query in Django Model - python

Trying to modify a Django project's filter.
I have the following query
queryset = Post.objects.filter(public=True)
I want to modify this to have the query ordered by 'like_count'
How would I implement this?

By using order_by, like this:
q = Post.objects.filter(public=True).order_by('like_count')

If Like is a different table.
The solution in the below link might help.
Django, annotation and ordering using data from other table

Related

Aggregate tag names in Django Taggit

I am using the django taggit library. I have a Queryset that lists objects, which have a few tags attached to each object. How to get them all in one query?
While I know how to get tags for each objects on model level, I haven't found a way to do so at Queryset level. How to get all objects tags in Queryset in the same query?
Something like
Book.objects.filter(year=2020).values('bookname', 'published_at', 'tag_names_list')[:]
Queryset.values('main_group_field').annotate(all_tags=StringAgg('tags__name', ',')) solves it.

Django form field queryset optimization

I have a form like this on Django app:
class CustomForm(forms.Form):
field1 = forms.ModelChoiceField(queryset=ModelA.objects.filter(type=A))
field2 = forms.ModelChoiceField(queryset=ModelA.objects.filter(type=B))
The Debug Toolbar tells me there are two duplicates querys on ModelA but the filter conditions it's different. Is this a bug?. Also I was wondering if there is a way to optimize this case and make only one query
Thanks!
ModelA.objects.filter(type=A) and ModelA.objects.filter(type=B) are two separate querysets, so require two queries.
In theory, you could do
ModelA.objects.filter(type__in=[A, B])
Which would get all objects where type=A or type=B. You could then filter the list in Python. However, this wouldn't necessarily perform any better. You wouldn't be able to use the ModelChoiceField any more, so your code would be more complicated.

Building Custom Query with filters in Django

I'm trying to make a custom query in django based on some filters located in the template. Should be something similar with the View tickets section from Django official website
My template should have some inputs for predefined columns in the Filter section and based on the given values should filter the results.
I found some topics related to Q objects, but I'm not sure how to build the queries based on the values from UI.
Do you have any ideas?
Q objects is use for SQL OR and AND e.g
Select * From Country Where Country_Name LIKE "India" OR Country_Name LIKE "Pakistan"
Q(question__startswith='Who') | Q(question__startswith='What')
This is equivalent to the following SQL WHERE clause:
WHERE question LIKE 'Who%' OR question LIKE 'What%'
https://docs.djangoproject.com/en/1.9/topics/db/queries/#complex-lookups-with-q-objects
We've implemented a query builder, akin to what you're suggesting, for the django admin over at django-advanced-filters.
You can probably copy paste the form/s and related templates for a similar effect outside of the admin.

How can I filter a Haystack SearchQuerySet for None on an IntegerField

This is driving me a bit mad but seems like it should be simple.
I'm using Django and Haystack and have a search index including an IntegerField which allows null. This is based on a related model in Django, but I don't think this matters. eg:
class ThingIndex(indexes.ModelSearchIndex, indexes.Indexable):
group = indexes.IntegerField(model_attr='group__id', null=True)
class Meta:
model = Thing
I sometimes want my Haystack query to return items with None/Null for this field, so I'm filtering in the search form's __init__, but I can't get a query to do this. The most obvious way I tried was:
self.searchqueryset.filter(group__isnull=True) # how to do it on a regular Django queryset
But this returns no records.
Right now I'm working around it with this:
self.searchqueryset.exclude(group__in=range(1,100))
Which works, but obviously isn't the way it should be done :)
Can anyone help?
Thanks!
I feel this question was not answered. It seems the op was asking how to filter for null entries using haystack.query.SearchQuerySet with an ElasticSearch backend.
In the example above, replace
self.searchqueryset.filter(group__isnull=True)
with
self.searchqueryset.filter(_missing_='group')
Not intuitive, but its the only way I have gotten this to work so far.
If you are using ElasticSearch, the solution can be done without patching, just using native ElasticSearch:
from haystack.inputs import Raw
self.searchqueryset.exclude(group = Raw("[* TO *]"))
Other way around, filter all documents that have non-emtpy group field:
from haystack.inputs import Raw
self.searchqueryset.filter(group = Raw("[* TO *]"))
This could work for SOLR too and for other Haystack backends applying the same concept but with specific syntax of the backend search language.
References:
Elastic search query syntax
Haystack backend implementation for elasticsearch
Haystack Raw input field
Thanks to #AlexParakhnevich who provided this link which served me as an inspiration.
Good to know that Elasticsearch also supports special and more robust "missing" filter
If you're using SOLR, you'd probably like to have a look at the following links:
1) https://github.com/toastdriven/django-haystack/commit/9332a91a7f0e4b33d7e20aa892d156305c12dfe3
2) https://github.com/toastdriven/django-haystack/issues/163
There's a patch for SOLR, allowing such queries, but for other backends there's probably none.

Queryset-like filtering of object collection in Django

I'm looking for a way to easily filter from a collection of Model objects without hitting the database each time. By definition, QuerySets are lazy and always will hit the DB. So I am wondering if there is anything existing that can do this. If not, perhaps its a good library to create.
For example:
all_records = object_set(Record.objects.filter(company=user.company))
object_set being a hypothetical function which would gather all of the objects in a QuerySet as static data. The result would be an "object manager" instance that could have filters run against it similar to QuerySet filters. This would be particularly useful in storing creating, updating, and deleting objects based on data from multidimensional lists of data.
for row in data:
for col in row:
# this would not hit the DB. Only filter within the "object_set" in memory.
all_records.filter(date=col.date, type=col.type, creator=col.user)
I realize I may be trying to solve this the wrong way, but regardless, I think this would be a great tool to have in Django. Does anyone know of an existing library or functionality within Django that would solve this problem? Thanks in advance!
I think the QuerySet's select_related method is what you want:
https://docs.djangoproject.com/en/dev/ref/models/querysets/#select-related
Please, check out the managers.py in the following project: django-model-utils/.../managers.py
It should show you how he implemented the queryset
def get_query_set(self):
qs = super(QueryManager, self).get_query_set().filter(self._q)
if self._order_by is not None:
return qs.order_by(*self._order_by)
return qs
If long datasets is your motivation for this question use Redis cache in your Django project.
http://unfoldthat.com/2011/09/14/try-redis-instead.html

Categories