How can I make a query with contains over date/datetime fields - django

Im trying to use the datatables jQuery plugin with date/datetime fields. and when you make the query that contains those field generates a MySQL Warning when you try to use __contains in the queryset. I've detected that if you try to make queries over Year, Month and Day the warning doesn't appears.
There's another way to search in a date/datetime field without raise that warning or how could I make a query over a year/month/day in a date/datetime field.
Here is an example:
Model.objects.filter(Date__contains="2014")
Which gives this warning:
Warning: Incorrect date value: '%2014%' for column 'Fecha' at row 1
I'd like to make a query like this:
SELECT * FROM Model WHERE YEAR(Date) LIKE "%4%" OR MONTH(Date) LIKE "%4%" OR DAY(Date) LIKE "%4%";

The best solution that I´ve found is searching by a Regex
Model.objects.filter(Date__regex="4")

Model.objects.filter(field_name__year=2014)

Related

Add extra field and value to django query set

Hi I am doing a query like
user_list = Myuser.objects.filter(status=active)
now I want to add a new filed matching_percentage to a user who query it , Like want to show how much it matches to your profile. Now I searched annotate function but till now I found that you cant assign a custom calculated value to new filed .
So Is there any way to assign to a filed int values to show how much it matches my profile on run time by a algorithm ?
Update
I am trying something like this
query=MyUser.objects.annotate(annotated_field=Value(MyFunction(F('id')), output_field=IntegerField()))\
.filter(id__in=ids)
F('id') is not converting to ID just passing in function as a string

Extract date from django query

I have a query with the date filter.
queryset=Model.objects.filter(order_created_on__gte='2018-10-10')
It constructs a query like this -
"Model"."order_created_on" >= 2018-10-10 00:00:00+05:30
Which gives an error for that '00:00:00+05:30' when I qun the query. The queryset populates the data properly, but I want it to run via query.
An alternative is to use 'order_created_on__date__gte' but its giving an error, thinkso date filter is not available with __gte.
Another alternative is to construct my filters such - 'order_created_on__range=['2018-10-10 00:00:00+05:30']'.
Any other alternative available?
You can use
queryset=Model.objects.filter(order_created_on__year__gte=2018, order_created_on__month__gte=10, order_created_on__date__gte=10)
or simply
queryset= Model.objects.filter(order_created_on__gte=datetime.date(2010, 10, 10))

Django order_by() filter with distinct()

How can I make an order_by like this ....
p = Product.objects.filter(vendornumber='403516006')\
.order_by('-created').distinct('vendor__name')
The problem is that I have multiple vendors with the same name, and I only want the latest product by the vendor ..
Hope it makes sense?
I got this DB error:
SELECT DISTINCT ON expressions must match initial ORDER BY expressions
LINE 1: SELECT DISTINCT ON ("search_vendor"."name")
"search_product"...
Based on your error message and this other question, it seems to me this would fix it:
p = Product.objects.filter(vendornumber='403516006')\
.order_by('vendor__name', '-created').distinct('vendor__name')
That is, it seems that the DISTINCT ON expression(s) must match the leftmost ORDER BY expression(s). So by making the column you use in distinct as the first column in the order_by, I think it should work.
Just matching leftmost order_by() arg and distinct() did not work for me, producing the same error (Django 1.8.7 bug or a feature)?
qs.order_by('project').distinct('project')
however it worked when I changed to:
qs.order_by('project__id').distinct('project')
and I do not even have multiple order_by args.
In case you are hoping to use a separate field for distinct and order by another field you can use the below code
from django.db.models import Subquery
Model.objects.filter(
pk__in=Subquery(
Model.objects.all().distinct('foo').values('pk')
)
).order_by('bar')
I had a similar issue but then with related fields. With just adding the related field in distinct(), I didn't get the right results.
I wanted to sort by room__name keeping the person (linked to residency ) unique. Repeating the related field as per the below fixed my issue:
.order_by('room__name', 'residency__person', ).distinct('room__name', 'residency__person')
See also these related posts:
ProgrammingError: when using order_by and distinct together in django
django distinct and order_by
Postgresql DISTINCT ON with different ORDER BY

How can I select multiple columns from a Django model?

At the moment I have a query that selects distinct values from a model:
Meeting.objects.values('club').distinct()
In addition to the 'club' field, I also wish to select a 'time' field. In other words I wish to select distinct values of the 'club' field and the associated 'time' field. For example for:
CLUB,TIME
ABC1,10:35
ABC2,10:45
ABC2,10:51
ABC3,11:42
I would want:
ABC1,10:35
ABC2,10:45
ABC3,11:42
What is the syntax for this?
This is possible, but only if your database backend is PostgreSQL. Here how it can be done:
Meeting.objects.order_by('club', 'time').values('club', 'time').distinct('club')
Look documentation for distinct

Getting most recent instance of each category in a queryset

I've got a model 'Thing' with these fields:
name: TextField
category: TextField
date: DateField
I first do an icontains query on name:
Thing.objects.filter(name__icontaints='substring')
My question is how to filter that result to only give the most recent item in each category.
If I get three results with a category of 'widget' I only want one widget in the result set - the most recent one.
My naive solution would be to iterate through the queryset, keep a record of most recent dates and construct a new result set. Is there a better way? One that preferably works at the database level.
Unfortunately there is no way to do this reliably across all databases since the queries vary quite a bit.
With MySQL you could do something like this:
SELECT
name,
category,
date
FROM
thing
WHERE
name LIKE '%substring%'
GROUP BY date
With PostgreSQL it would be something like this:
SELECT
DISTINCT ON (category)
name,
category,
date
FROM
thing
WHERE
name LIKE '%substring%'
ORDER BY date DESC
If you are using PostgreSQL, than you can use this patch to get DISTINCT ON support: http://code.djangoproject.com/ticket/6422