Search code examples
pythondjangodjango-orm

Exclude duplicate elements with lower priority (Django)


I have the following model:

class Action(BaseModel):
    action_id = models.IntegerField(unique=True, db_index=True)
    name = models.CharField(max_length=25)
    object = models.CharField(max_length=25)
    priority = models.IntegerField(default=0)

Suppose there are two 4 objects:

{"action_id":1, "name":"read", "object":"post", "priority":1}
{"action_id":2, "name":"write", "object":"post", "priority":2}
{"action_id":3, "name":"read", "object":"user", "priority":1}
{"action_id":4, "name":"update", "object":"user", "priority":2}

How can I filter out objects with the same object value, and leave only those with a priority higher in the duplicate set?

[{"action_id":2, "name":"write", "object":"post", "priority":2}, {"action_id":4, "name":"update", "object":"user", "priority":2}] 

I tried filtering methods with - annotate, Max, Count and filter but duplicates are returned if i filter by priority


Solution

  • You filter out items if there is an item with the same object, but a higher precedence, so:

    from django.db.models import Exists, OuterRef
    
    Action.objects.filter(
        ~Exists(
            Action.objects.filter(
                object=OuterRef('object'), priority__gt=OuterRef('priority')
            )
        )
    )