简体   繁体   中英

Creating model for unordered list in Django

What is the best approach to create a model field in Django, so that in template, I can iterate over its objects as:

<ul>
    {% for item in ModelName.fieldname %}
        <li>{{ item }}</li>
    {% endfor %}
</ul>

so It output something like, lets say:

<h1>Apple Products</h1>
<ul>
  <li>Ipod</li>
  <li>Apple</li>
  <li>Ipod mini</li>
  <li>Display XDR</li>
  <li>Macbook Pro</li>
</ul>

My thoughts:

  • Create a separate model and then reference it as foreign key to parent model.
  • create a CharField and separate each list item with comma, then create a function; return a list and loop over list of separated items by comma.

Kindly share your idea, what is better approach and professional way to do this. Thank you.

Here you go >>>>In models.py

class Category(models.Model):
   name  = models.CharField(max_length=50, null=True, blank=True, unique=True)

class Product(models.Model):
  name       = models.CharField(max_length=80, null=True, blank=True, unique=True)
  category   = models.ForeignKey(Category, on_delete=models.CASCADE, null=True, blank=True)

In your views.py ::

def myView(request):
   my_list = []
   all_prd = Product.objects.all()
   all_cat = Category.objects.all()
   for cat in all_cat:
      temp = list(all_prd.objects.filter(category__name = cat ))
      my_list.append(temp)
   my_list = list(filter(None, my_list)
   context = [
      'my_list' : my_list,
   ]
   return(request, 'cute.html' , context)

In cute.html ::

<ul>
   {% for item in my_list %}
       {% for prd in item %}
          {{prd.name}}
       {% endfor %}
      <br>
      <br>
   {% endfor %}
</ul>
  

I gave you a hint.modify it like you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM