danny
danny

Reputation: 11

django query for sorting the data on a field present as foreign key

class abc(xyz):
    user = models.ForeignKey(User, max_length=100)

What'll be the django query for sorting the data based on a foreign key field?

I tried with query:

  abc.objects.filter(User__user=user).
  abc.objects.filter(Q(user__icontains=search_query) ).

I have done this 2 queries, But dont know how to combine & make it work

I don't know how to proceed. Can someone please lend a helping hand?

Upvotes: 1

Views: 542

Answers (2)

Mohammad Mustaqeem
Mohammad Mustaqeem

Reputation: 1084

I believe you want to sort by user's username. You can do it by:

abc.objects.all().order_by('user__username')

Look at the docs for details.

Note the double underscore '__' here. It is required to separate the foreignkey's field from foreignkey by double underscore while referring foreignkey's field.

Upvotes: 0

user2390182
user2390182

Reputation: 73460

The first query does not work with your model. Change it to

qs = abc.objects.filter(user=user) 

Now, sorting this queryset by user (or user_id or any other user's property which would work)

qs = qs.order_by('user_id')

wouldn't make much sense as all elements in your queryset have the same user.

The second query does not work since icontains is a query that works for strings whereas user is a model instance. The following might work:

 abc.objects.filter(user__username__icontains=search_query)  # .order_by('user__username')

Generally, you can order by properties that have a (natural) order, like ints, floats, strings, dates, etc. Thus, you can order by sth. like user_id, user__username, user__email, user__date_joined:

abc.objects.all().order_by('user_id')  # for instance

Upvotes: 1

Related Questions