Django Get() Returned More Than One Object
Solution 1:
get
expected to returns single item with desired criteria, else (nothing or more than one) raise an exception. If you want to select any number of items with desired criteria, you can use filter
instead.
def write_pdf_view(request):
if request.method == 'POST':
reference = request.POST.get('Reference_IDs')
manifest_queryset = Manifests.objects.filter(reference=reference)
order = Orders.objects.get(reference=reference)
Then you can iterate the selected manifests and get the value of each manifest related field by using dot notation.
for manifest in manifest_queryset:
print(manifest.description)
Also you can get list of descriptions by using values_list
.
description_list = manifest_queryset.values_list('description', flat=True)
You can get more information in QuerySet API reference.
Solution 2:
For your first question you can use filter()
method for getting specific records from your model.
def write_pdf_view(request):
if request.method == 'POST':
reference = request.POST.get('Reference_IDs')
manifest = Manifests.objects.filter(reference=reference)
order = Orders.objects.get(reference=reference)
For your second question, filter()
returns a queryset.So you can access the data by iterating over the queryset or by the index.
fordatain manifest:
print(data.description)
For your information get() returns an object and throws an exception if no object is found while filter() returns an empty list.
Solution 3:
To get multiple data you can use the filter property.
order = Orders.objects.all().filter(reference=reference)
manifest = Manifest.objects.all().filter(reference=reference)
Solution 4:
Use filter()
instead of get()
.
But the filter returns queryset not object. So you have to loop through queryset.
def write_pdf_view(request):
if request.method == 'POST':
reference = request.POST.get('Reference_IDs')
y = Orders.objects.all()
z = Manifests.objects.all()
order = y.get(reference=reference)
manifest = z.filter(reference=reference)
for manifest_value in manifest:
print(manifest_value.description)
For more details about queryset see QuerySet API
Solution 5:
to get specific item by unique fields you can use get
. will raise DoesNotExist
if no object found.
order = Orders.objects.get(pk=reference)
if you want list of objects use filter
. will default to []
if can't find any.
manifest = Manifest.objects.filter(reference=reference)
Post a Comment for "Django Get() Returned More Than One Object"