Possible to use distinct() with attributes created via extra() in Django ORM?

Let’s say you have the following Django ORM query:

cars = CarModel.objects.only(
            'is_position_paper': 'cartype_id = 7',
            'is_null_date': 'cardate IS NULL',
            'shorttitle': extra,
    ).filter(**kwargs).distinct(sort_order_for_distinct, 'car__car_id').order_by(sort_order, 'car__car_id')

My understanding is that, whatever I’ve included in order_by() I have to also include, in the same order, in distinct(). However, distinct doesn’t like the attributes being created in extra(). If I try and include these attributes in the order_by() as I would like, such as:

.order_by('is_position_paper', 'is_null_date', sort_order, 'car__car_id')

I get the error:

Cannot resolve keyword ‘is_position_paper’ into field

So that means that the attributes created via extra() just aren’t going to be available to use with distinct()? Is there any alternative approach here?

Really all I’m trying to do is dedupe this entire queryset by car__car_id, that’s it, whilst having order_by('is_position_paper', 'is_null_date', sort_order, 'car__car_id')

Unfortunately I’m stuck on Django 2.1 with this. Also, using Postgres as the db.

Without having a copy of your models and enough data to do some playing around with this, all I can do is make some general observations.

What jumps out at me is that cartype_id and cardate aren’t elements of CarModel. My first thought is that those references should be car__cartype_id and car__cardate.

If I were working on this, I’d be trying to build this in the Django interactive shell, looking at the queries being generated to understand what the ORM is trying to do.


Thanks, it took over a day to get my new account approved so by the time this was finally posted I ended up just making two queries and using one query w/distinct() as a dedupe data set to filter the original query with. Not ideal, but it works well after going down the rabbit hole of trying to update extra() statements with annotate() (because I needed parameters in order_buy() that I couldn’t pass to distinct() because the were being created via extra(), so I made them via annotate() ) only to then find out I can use annotate() and distinct() together? I was getting NotImplementedError: annotate() + distinct(fields) is not implemented error. Anyway, very frustrating overall,