2

Can I combine the use of filter() and get() on querysets to return an object in a django view? I have the following view;

def my_view(request, city, store, item):
item = Item.objects.filter(store__city=city, city=city).get(item=item)

Items are all unique for city and store. I am currently trying to filter a queryset based on the two ForeignKey fields and then use get on a CharField but am getting an error message that the object does not exist. Am I approaching this incorrectly or is my syntax off somewhere? Thanks

thesteve
  • 2,413
  • 6
  • 26
  • 28

1 Answers1

1

If your related filter returns only 1 result, then you can use :

def my_view(request, city, store, item):
    item = Item.objects.filter(store__city=city, city=city)[0]

which filters the Item records and store them in a QuerySet, which has a list-lilke structure, then take the first element...

If you are sure to get a result, then you can use get instead of filter:

item = Item.objects.get(store__city=city, city=city)

But if there exists no record which fits your filer criteria, then you get an error. So if you are not sure whether filtering will return a result or not, then use:

item = Item.objects.filter(store__city=city, city=city)
if item:
    item = item[0]

which ckecks the resulting queryset and takes the first result if exists any.

Mp0int
  • 18,172
  • 15
  • 83
  • 114