In Django using fiter() then get() on queryset? -
can combine use of filter() , get() on querysets return object in django view? have following view;
def my_view(request, city, store, item): item = item.objects.filter(store__city=city, city=city).get(item=item)
items unique city , store. trying filter queryset based on 2 foreignkey fields , use on charfield getting error message object not exist. approaching incorrectly or syntax off somewhere? thanks
if related filter returns 1 result, can use :
def my_view(request, city, store, item): item = item.objects.filter(store__city=city, city=city)[0]
which filters item records , store them in queryset, has list-lilke structure, take first element...
if sure result, can use instead of filter:
item = item.objects.get(store__city=city, city=city)
but if there exists no record fits filer criteria, error. if not sure whether filtering return result or not, use:
item = item.objects.filter(store__city=city, city=city) if item: item = item[0]
which ckecks resulting queryset , takes first result if exists any.
Comments
Post a Comment