Cannot use distinct w/ a different Order by using Django ORM - django

I have seen a few posts that reference this issue on Stackoverflow, but I cannot figure out how to get the business need solved, if the query changes.
I am trying to get the last 10 contacts that have sent a message to the organization
messages = (Message.objects.order_by('-created_at').distinct('contact_id'))
However, I get this error:
SELECT DISTINCT ON expressions must match initial ORDER BY expressions
LINE 1: SELECT DISTINCT ON ("messages"."contact_id") "messages"."id"...
I see that the distinct column must match the order by column, but a distinct created_at, isn't what the business needs to solve the problem.
Any suggestions?

The field in distinct() must be included and must be the first one in order_by(), in your case contact_id:
Message.objects.order_by('contact_id', '-created_at').distinct('contact_id')
Docs: https://docs.djangoproject.com/en/dev/ref/models/querysets/#distinct

Related

POWERBI: take while table when there is no available relation

I have a slight issue with my tables in POWERBI. In short, I have a missing link in one of my relations. As a result, instead of returning NOTHING which is logical and actually what I would like, it returns EVERYTHING.
A bit more details, I have the multiple tables with relations between them. The problem is that I have a few task_group pointing toward shipments that do not exist. In my visualization, I am trying to access data (a count of the number of Packages linked to a shipment) that is linked to a shipment. The logical thing for me would be that "If there is no shipment fitting the number that is given in the shipment table, then you cannot count the number of packages linked to that shipment".
But PowerBI beg to differ. His idea is "If I cannot find a shipment to link to package, i'm going to take every single package regardless of shipment". As a result, a group of task that do not have any package end up showing as having all the packages instead. How can I tell powerbi to return nothing if he doesn't find anything instead of returning everything?
Image of my relationships
I think Power BI behaves slightly unintuitively where there are nulls on one side of a join.
Have you tried filtering to only include where shipment_id is not blank?
If the problem is you having NULLs in one side of the relationship, the best way to tackle this would be to replace the NULLs with something else. Now, you can do it in two ways:
Edit the Shipment number NULLs to something else in the Power query while importing (Some number which is not likely to be an actual shipment, maybe 0)
Create a calculated field in DAX replacing the blanks/NULLs and use that in the relationship instead
But I think you may have NULLs in both the sides of the relationship. That is the only explanation I can think of, why Power BI is behaving this way. Either way, the above solutions should fix it.

Django Query, Distinct and Order_By combination not working

There are similar questions here but I haven't been able to find one that helps me.
I have two models, Chat and Post
there are multiple Chats, and each chat has multiple posts attached to it.
I'm trying to get the latest post for each chat.
Post.objects.order_by('-id').distinct('Chat')
Filter the posts by ID (so the newest post is first), and then grab the distinct ones based on the Chats.
but since order_by and distinct don't match I'm getting the error:
SELECT DISTINCT ON expressions must match initial ORDER BY expressions
So how exactly do I go about doing this? Rawsql? Thanks!
If you use distinct by related model, you must use ordering based of this model:
Post.objects.order_by('chat', '-id').distinct('chat')
Also you can look at this question

How to Replace Specific value with other value in django database column?

I have a Table "Subscriber" in which one column whose name is Status.
I want to replace value of "status" column.Where status = 1 and 3 change it with 4. In other words all '1 and 3' status convert into 4.
What should i do to solve this problem.
#e4c5's solution is perfectly good, though I try to reserve Q objects for complex queries, in this case, I might just go with the __in filter: Subscriber.objects.filter(status__in=[1, 3]).update(status=4)
Use a Q object to get the OR condition. The rest of it is a simple call to update
Subscriber.objects.filter(Q(status=1)|Q(status=3)).update(status=4)
Keyword argument queries – in filter(), etc. – are “AND”ed together.
If you need to execute more complex queries (for example, queries with
OR statements), you can use Q objects.
Read the documentation for update here: https://docs.djangoproject.com/en/1.9/ref/models/querysets/#update

update a queryset in a specific order

I have a "index" field stores a consequent range of integers, for safety i set it unique.
now I want to increase this field by one, to keep unique I update the value in a descending order:
MyModel.objects.all().order_by('-index').update(index=F('index')+1)
what surprises me is that on some machine an IntegrityError
gets raised and complains for duplicated index value.
is there anything i missed? could I only save records one by one?
thanks in advance!
UPDATE:
I think the root problem is that there is no ORDER BY in an SQL UPDATE command (see UPDATE with ORDER BY, and also SQL Server: UPDATE a table by using ORDER BY)
Obviously django simply translates my statement into a SQL UPDATE with ORDER_BY, which leads to an undefined behavior and creates different result per machine.
You are ordering the queryset ascending. You can make it descending by adding the '-' to the field name in the order by:
MyModel.objects.all().order_by('-index').update(index=F('index')+1)
Django docs for order_by

Simple SubSonic 3 Generation issues

I'm trying to do a proof of concept using SubSonic 3 but Sstraight away i'm hitting numerous errors with the generation. I started making alterations to the generator settings but that seems a little odd when I'm just trying to do a simple one to one mapping of my DB.
Firstly I found an SP that had #delagate as an SP parameter name, this was easily fixed, but should probably be in the standard templates as a user shouldn't have to make template changes for this simple an issue.
Next I found that the system choked on two tables and tried to create signatures the same
the tables where
Field
Fields
now i know SubSonix 2 had a fixPluralClassName property but buggered if I can find one in the template for SubSonic 3
Any help on that one will get me started
Generally 'X' and 'Datum' type appendages/substitutions happen when you have used a 'reserved' word in a column or table name. In this case 'Reserved' being a word that Subsonic doesn't like to use for data objects.
A couple of rules I follow are;
Ensure both table names and column
names are not 'reserved' words (ie
'Data' or 'Int' or 'Table')
Ensure that each table has a primary key
Don't use date and time column types
as they are not supported yet
(DateTime is, just not Date and Time types)
Don't have a column with the same
name as the table
The Subsonic FAQ might be helpful.