Search code examples
pythondjangodjango-orm

how can I show multiple objects of a multiple objects using django ORM?


if co is None:
    try:
      address = **Contract**.objects.filter(address= servicesearch)
      print(address)
    except Contract.DoesNotExist:
      address= None

    for add in address:
      co = add.contractservices_set.all()
      print(co)

the first query yields <QuerySet [<Contract: Contract object (52)>, <Contract: Contract object (55)>]>

the second query yields <QuerySet [<Contractservices: Contractservices object (88)>, <Contractservices: Contractservices object (89)>, <Contractservices: Contractservices object (90)>, <Contractservices: Contractservices object (91)>]> <QuerySet [<Contractservices: Contractservices object (98)>, <Contractservices: Contractservices object (101)>, <Contractservices: Contractservices object (102)>, <Contractservices: Contractservices object (99)>, <Contractservices: Contractservices object (103)>, <Contractservices: Contractservices object (100)>, <Contractservices: Contractservices object (104)>]>

All Good....

However, when I am trying to render the results its only showing the **contract **objects of 55. I want to show both **contract **objects 52 and 55. please help...

my paginator view is..

 paginator = Paginator(co,8)
    if request.GET.get('page') == None:
        page_number = 1
    else:
        page_number =request.GET.get('page')
      
    DataFinal=paginator.get_page(page_number)
    totalpage =DataFinal.paginator.num_pages

I cant change the template as it is just one search criteria among many.. your text


Solution

  • You have set only co in the paginated result.

    You have to set only one query for getting Contract with ContractServices attached together:

    address = Contract.objects.filter(address=servicesearch)
    address = address.prefetch_related("contractservices_set")
    
    ...
    
    paginator = Paginator(address, 8)
    if request.GET.get('page') == None:
        page_number = 1
    else:
        page_number =request.GET.get('page')
          
    DataFinal = paginator.get_page(page_number)
    
    ...
    # in the html
    {% for address in DataFinal %}
        {% for service in address.contractservices_set.all %}
            {{service.XXX}}
        {% endfor %}
    {% endfor %}