Rewriting "SELECT DISTINCT ON ..." using Django ORM

I am using the following model with Django:

class Hit(Model):
    image = ForeignKey(Image)
    user = ForeignKey(User)
    timestamp = DateTimeField(auto_now_add = True)

I basically need a list containing the number of “first hits” (ie hits with an earlier timestamp for the same image) for each user to create a list of ranks.

Or even simpler, just a list that contains the username once for each time that user made the “first hit”.

In SQL, using the PostgreSQL extension "DISTINCT ON", this will be a simple query like:

SELECT DISTINCT ON (image_id) user_id FROM proj_hit ORDER BY image_id ASC, timestamp ASC;

Is there a way to get this result with Django ORM or (at least) portable SQL, i.e. no PostgreSQL extensions?

+3
source share
2

? - .

,

class Hit(Model):
    image = ForeignKey(Image)
    user = ForeignKey(User)
    timestamp = DateTimeField(auto_now_add = True)
    is_first_hit = BooleanField(default = False)

save() ( ), is_first_hit . , .

+3

, SQL , , - ON:

SELECT DISTINCT image_id, user_id FROM proj_hit ORDER BY image_id ASC, timestamp ASC;
0

Source: https://habr.com/ru/post/1765463/


All Articles