Home > Mobile >  Return a distinct order based on In Query
Return a distinct order based on In Query

Time:10-30

I have a queryset where I want to return the respective order based on my values inside the in filter. Below are my given syntax and models

Models

class Transaction(models.Model):
    user = models.ForeignKey(Profile, on_delete=models.SET_NULL, null=True)
    comments = models.TextField(null=True, blank=True)


class Profile(models.Model):
    user = models.OneToOneField(User,
                                null=True,
                                blank=True,
                                related_name='profile',
                                on_delete=models.SET_NULL)
    first_name = models.CharField(max_length=125, null=True, blank=True)
    middle_name = models.CharField(max_length=125, null=True, blank=True)
    last_name = models.CharField(max_length=125, null=True, blank=True)
    nickname = models.CharField(max_length=100, null=True, blank=True)
    balance = models.DecimalField(default=0.0, max_digits=7, decimal_places=2)
    is_online = models.BooleanField(default=False)

Syntax

from trading.models import Transaction
ids = [4, 1, 3, 2]
tx = Transaction.objects.filter(user_id__in=ids).order_by('user').distinct('user')

Where I expect that the returned order of Transaction object is based on the id order of the list of ids

CodePudding user response:

i had the same problem this how i solved it.this will work if you use Django >= 1.8

from django.db.models import Case, When
from trading.models import Transaction
ids = [4, 1, 3, 2]
myorder = Case(*[When(user_id=id, then=pos) for pos, id in enumerate(ids)])
txt = Transaction.objects.filter(user_id__in=ids).order_by(myorder)

CodePudding user response:

There is already a good answer above but I still want to share my answer and I did it in Python application level. The answer above looks better. Take note, that this worked with Django Rest Framework

ids = [4, 2, 3, 1]
transactions = Transaction.objects.filter(user_id__in=ids).order_by('user').distinct('user')
reorder_basis = {transaction.user_id: transaction for transaction in transactions}
reordered_transactions = [reorder_basis.get(_id) for _id in ids]
  • Related