Home > other >  How to convert QuerySet string intro String in Django template?
How to convert QuerySet string intro String in Django template?

Time:06-15

Django template shows the categories as for example <QuerySet [<Category: Fashion>]> I want it to show just as Fashion.

index.html

{% for auction in auctions %}
        <li>Auction: {{ auction.title }} Content: {{ auction.content }} Price: {{auction.price}} Category: {{ auction.category.all|slice:":1" }} <img src="{{auction.pic}}" alt="{{auction.title}} pic">  </li>
    {% endfor %}

models.py

class Category(models.Model):
    FOOD = 'FO'
    TOYS = 'TO'
    FASHION = 'FA'
    ELECTRONICS = 'EL'
    HOME = 'HO'
    NOTHING = 'NO'

    CHOICECATEGORY = (
            (FOOD,'Food'),
        (TOYS,'Toys'),
        (FASHION,'Fashion'),
        (ELECTRONICS,'Electronics'),
        (HOME,'Home')
        )
    category = models.CharField(max_length=300, choices=CHOICECATEGORY)
    
    def __str__(self):
        return self.category

class Auctionmodel(models.Model):
    title = models.CharField(max_length=300)
    content = models.TextField()
    price = models.IntegerField()
    pic = models.CharField(max_length=300, blank=True)
    category = models.ManyToManyField(Category, related_name='Category')
    categorysomething = Category.objects.filter(category=category).first()

views.py

def index(request):
    return render(request, "auctions/index.html", {
"auctions": Auctionmodel.objects.all()
    })

CodePudding user response:

If you have a QuerySet object then template will show this object's __repr__ method. To show internal objects you have to use for loop:

{% for category in auction.category.all %}
    {{ category }} {{ category.category }}
{% endfor %}

or if you really want it (but it's not good practice):

{{ auction.category.first }}
  • Related