我有一個名為 marketplace 的應用程式,在該應用程式中我有一個名為 Product 的模型,我希望能夠從中獲取資料以將其顯示在我的 html 檔案中,但它似乎無法正常作業。
這是模型:
class Product(models.Model):
product_id = models.AutoField(primary_key=True)
inventory = models.ForeignKey(ProductInventory, on_delete=models.CASCADE)
product_name = models.CharField(max_length=30)
product_description = models.CharField(max_length=250)
price = models.DecimalField(max_digits=10, decimal_places=2)
subscription_length = models.IntegerField()
這是views.py中使用的代碼
def product_page(request):
product_description = Product.objects.raw('SELECT product_description FROM marketplace_product WHERE product_name = "abcdef" ')
context = {'product_description': product_description}
return render(request, 'main/product-page.html', context)
這是最終結果,您可以看到它顯示的是查詢而不是結果資料。

如何讓它顯示 SQL 查詢的結果而不是查詢本身。謝謝
uj5u.com熱心網友回復:
首先,如果您正在執行無法使用 orm 完成的查詢,您真的應該只使用 raw。你想要的是
product_description = Product.objects.filter(product_name='abcdef').values('product_description')
其次,您將查詢集傳遞給您的模板。你需要用它做點什么......也許通過遍歷查詢集來創建一個包含所有產品描述的串列?
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/516891.html
下一篇:查找兩列的每個組合的MAX值
