简体   繁体   中英

Django Rest Framework : get_queryset returns 'detail': 'Not found'

Hi I have API which needs to perform Join table with subquery and return queryset. When I print queryset, it prints a queryset with one object in it, but returns 404 'detail': 'Not Found' error.

I get the customer id in URL, I have to query Customer table to get the corresponding address_id and send the address details of the address_id from Address table.

Below are the models

class Customer(models.Model):
    customer_id = models.AutoField(primary_key = True, auto_created = True)
    first_name = models.CharField(max_length = 45)
    last_name = models.CharField(max_length = 45)
    address_id = models.ForeignKey('Address', db_column = 'address_id', on_delete = models.CASCADE)

class Address(models.Model):
   address_id = models.AutoField(primary_key = True)
   district = models.CharField(max_length = 20 )
   postal_code = models.CharField(max_length = 10 , blank=True)
   phone = models.CharField(max_length = 20)

Below is the view

class AddressDetail(generics.RetrieveUpdateDestroyAPIView):

    lookup_url_kwarg = "customer_id"
    serializer_class = AddressSerializer
    
    def get_queryset(self):
        
        cust_id = self.kwargs['customer_id']
        
        customer_addr_id = Customer.objects.filter(customer_id = cust_id)
        return Address.objects.filter(address_id__in=customer_addr_id.values('address_id'))
        

Below is the url

path('<int:customer_id>/address',views.AddressDetail.as_view())

I could print and see object in query set but getting response 'Not found' at client side. Please let me know if I am missing out something.

QuerySet.values() returns a dict-like object with all keys set to string 'address_id' and values to 'address_id' value, to check the address existence, you can use values_list instead.

# also you can chain `.distinct()` in the end
Address.objects.filter(address_id__in=customer_addr_id.values_list('address_id', flat=True))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM