Search code examples
pythondjangoreportlab

Django Get() Returned More Than One Object


I am receiving the following error:

get() returned more than one Manifests -- it returned 2!

I understand this is because there are multiple records in the database with the same value, but I want to return ALL of those records, so I assume I need to use something other than .get but I'm not sure what/how.

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.get(reference=reference)

....

....

#Manifest
    p.drawString(30,620,'MANIFEST: ')
    p.drawString(30,605,manifest.description)

The issue is the manifest.description line. There are more than one records with the same "reference" in the database, and so they won't print. So my question is 2 parts:

1) how can I change manifest = z.get(reference=reference) so that I can access multiple records

2) how can I then access those records in place of "manifest.description"


Solution

  • 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.

    for data in 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.