Home > Mobile >  How to display query result in django
How to display query result in django

Time:10-18

I have an app called marketplace and in the app I have a model called Product that I want to be able to get data from to display it in my html file but it doesn't seem to be working.

Here is the model:

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()

Here is the code used in 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)

And here is the end result, as you can see it displays the query and not the result data. enter image description here

How can I make it display the result of the SQL query and not the query itself. Thanks

CodePudding user response:

First off, you really should only use raw if you are doing a query that cant be done with the orm. What you wanted was

product_description = Product.objects.filter(product_name='abcdef').values('product_description')

Secondly, you are passing a queryset to your template. You need to do something with it...maybe create a list with all the products descriptions by looping through the queryset?

  • Related