嗨,我有API,需要执行带有子查询的Join表并返回queryset。当我打印queryset时,它将打印其中包含一个对象的查询集,但返回404'detail':'Not Found'错误。
我在URL中获得了客户ID,我必须查询Customer表以获取相应的address_id 并从地址表发送address_id的地址详细信息。
以下是模型
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)
下面是视图
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'))
下面是网址
path('<int:customer_id>/address',views.AddressDetail.as_view())
我可以打印并查看查询集中的对象,但在客户端得到响应“未找到”。 如果我遗漏了一些东西,请告诉我。
答案 0 :(得分:0)
QuerySet.values()
返回一个类似dict的对象,其所有键都设置为字符串“ address_id”,值设置为“ address_id”值,要检查地址是否存在,可以改用values_list
。
# also you can chain `.distinct()` in the end
Address.objects.filter(address_id__in=customer_addr_id.values_list('address_id', flat=True))