我的模型上的过滤器函数返回我<查询集 []>



我的模型中有这些模型。py

我正试图发送我的购买详细信息,并将其作为JSON返回,但myModel.objects.filter函数返回一个空QuerySet对象

型号.py

class Purchase(models.Model):
total = models.IntegerField()
date = models.DateTimeField(auto_now=True)
user_phone = models.CharField(max_length=50)
id_user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
)
class Purchase_detail(models.Model):
id_product = models.ForeignKey(Product, on_delete=models.CASCADE)
id_purchase = models.ForeignKey(Purchase, on_delete=models.CASCADE)
quantity= models.IntegerField()
price = models.IntegerField()

但是当尝试执行Purchase_detail.objets.filter时不起作用

def see_purchase_detail(request, id):
if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
purchase_detail = json.loads(serializers.serialize(
'json',
Purchase_detail.objects.filter(id_purchase=id)
))
print(purchase_detail, Purchase_detail.objects.filter(id_purchase=id))
return JsonResponse({'details': purchase_detail}, safe=False)
else:
return JsonResponse({None}, safe=False)

我认为您的过滤器查询应该是这样的:

Purchase_detail.objects.filter(id_purchase__id=id))

这是因为ForeignKey在Django ORM中是如何工作的。查询中的id_purchasePurchase对象。

我认为重命名ForeignKey字段会更好。

class Purchase(models.Model):
total = models.IntegerField()
date = models.DateTimeField(auto_now=True)
user_phone = models.CharField(max_length=50)
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
)
class Purchase_detail(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
purchase = models.ForeignKey(Purchase, on_delete=models.CASCADE)
quantity= models.IntegerField()
price = models.IntegerField()

现在过滤器应该是这样的:

Purchase_detail.objects.filter(purchase__id=id))

相关内容

  • 没有找到相关文章

最新更新