Home > Software engineering >  What's the difference between _set() and filter() using a Foreign Key in django?
What's the difference between _set() and filter() using a Foreign Key in django?

Time:10-18

Let's say I have a User and Order model. Order has a fk User.

What's the difference between doing

def getorders(request):
    user = request.user
    orders = user.order_set.all()

and

def getorders(request):
    user = request.user
    orders = Order.objects.filter(user=user)

Both will return the same result, no ?

So what's the benefits to use _set instead of filter ?

CodePudding user response:

Both will return the same result, no ?

Yes, the two will result in the same query.

So what's the benefits to use _set instead of filter?

You can give the relation a different name with related_name=… [Django-doc], for example:

from django.conf import settings
from django.db import models

class Order(models.Model):
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='orders'
    )

In that case you access the orders with:

user.orders.all()

this code can be read as "all the orders of user" which is likely more clean than writing a queryset like Order.objects.filter(user=user).

  • Related