2

Suppose we have such a model:

class Membership(models.Model):
    person = models.ForeignKey(Person, on_delete=models.CASCADE)
    date_joined = models.DateField()
    invite_reason = models.CharField(max_length=64)

Can we put x as a variable inside the filter so that we can have different querysets by giving different args when calling the get_queryset function?

def get_queryset(x, y):
    queryset = Membership.objects.filter(x=y)
    return queryset
2
  • When will you call the get_queryset? In a class-based view, it is acalled by the view boilerplate. Commented Dec 12, 2020 at 12:57
  • Exactly what do you want to achieve? Right now you focus on how you want to achieve this, not what. Commented Dec 12, 2020 at 12:57

1 Answer 1

2

A Q object [Django-doc] can take a 2-tuple with as first item a string that specifies the "key" and as second item the "value", so you can filter with:

from django.db.models import Q

x = 'person_id'
y = 14

Membership.objects.filter(Q((x, y)))

to obtain the Memberships with person_id=14.

It however does not make much sense to use this in get_queryset in a class-based view, because that function has to respect its code contract, and adding extra parameters will not work: it simply expects a self, and an optional queryset. You can add extra optional parameters, but when the view calls the get_queryset it will not use these parameters, or at least not if you do not alter the boilerplate logic.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.