Home > Net >  how can I display category name of selected wallpaper
how can I display category name of selected wallpaper

Time:10-30

models.py

class Category(models.Model):
    category_name = models.CharField(max_length=100)

    def __str__(self):
        return self.category_name


class SubCategory(models.Model):
    sub = models.CharField(max_length=100)
    category = models.ForeignKey(Category,on_delete=models.CASCADE)      

    def __str__(self):
        return self.sub


class Wallpaper(models.Model):
    subcategory = models.ManyToManyField(SubCategory)

this is my view.py

def download(request, wallpaper_name):
    try:
        wallpaper = Wallpaper.objects.get(name=wallpaper_name)
       

context = {'wallpaper': wallpaper}
return render(request, 'Wallpaper/download.html', context)

on my download page how can I show categorty name of that specific wallpaper

CodePudding user response:

You can simply use this. Check this out docs.


def download(request, wallpaper_name):
    try:
        wallpaper = Wallpaper.objects.get(name=wallpaper_name)
        categories_name = wallpaper.subcategory.values_list(
                "category__category_name", 
                flat=True
        ).distinct("category")
    ....

CodePudding user response:

A quick and dirty solution is get all the subcategory from the wallpaper that you just found. Then get the category_name of each subcategory:

def download(request, wallpaper_name):
    try:
        wallpaper = Wallpaper.objects.get(name=wallpaper_name)
       subcategories = wallpaper.subcategory.all()
       category_names = [cat.category_name for cat in subcatedories]
  • Related