Reputation: 4501
It often happens in my Django code that I have to make some operations with an object and then pass it on to other function in a form of a queryset. For now, I take the id of the object and query the database, which seems like junk code since I already have all data.
Better illustrated by an example:
obj = MyModelSerializer(data)
obj.save()
qs = MyModel.objects.filter(id = obj.id).values() # queries db just to get a queryset representation of a single object
return render(request, 'test.html', {'qs': qs})
Is there any better way to overwrite this code? Or it is perfectly ok ?
Upvotes: 3
Views: 1058
Reputation: 678
Assuming the test.html
template needs a QuerySet you're code is fine the way it is. Refetching the data is inefficient, but there is no documented way to populate a QuerySet except through the database.
You don't give an example test.html
but in many cases you could skip the QuerySet and pass a list instead, for example:
obj = MyModelSerializer(data)
obj.save()
return render(request, 'test.html', {'qs': [obj]})
Upvotes: 3