xemexpress
xemexpress

Reputation: 262

Django: How to get parameters used in filter() from a QuerySet?

For the following QuerySet,

qs = MyModel.objects.filter(attribute_one='value 1', attribute_two='value 2')

How can I retrieve the parameters used in the filter (i.e. attribute_one and attribute_two) and the corresponding values (i.e. value 1 and value 2) from qs?

Thank you!

Upvotes: 1

Views: 2397

Answers (2)

Ahtisham
Ahtisham

Reputation: 10126

You can use values as mentioned in comment. From the docs:

Returns a QuerySet that returns dictionaries, rather than model instances, when used as an iterable.

qs = MyModel.objects.filter(
   attribute_one='value 1', attribute_two='value 2'
).values('attribute_one', 'attribute_two')

for q in qs:
  for key, value in q.items():
    # key as attribute_one
    # value as value_1
    # and so on

Upvotes: 1

Ryan Thomas
Ryan Thomas

Reputation: 536

You have to loop through it, even though there only may be one item in qs.

    for i in qs:
        print(i.value1)

    or just do...

    for qs in MyModel.objects.filter(
        attribute_one='value 1', attribute_two='value 2'):

        print(qs.value1)

    Alternatively if it is one object you are after use 'get'

    MyModel.objects.get(
        attribute_one='value 1', attribute_two='value 2')

Upvotes: 0

Related Questions