社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Django

将queryset分组为django类别

Nick • 3 年前 • 1576 次点击  

我有一个 Ingredient 模型和a Shopping 一个购物清单的模型,我想在购物清单视图中按其类别对成分进行分组。是否有数据库方法来实现这一点,或者是否将运行视图中的for循环。最简单吗?

下图正是我想在购物清单视图中实现的目标:

html:

{% for key, value_list  in shoppingList.items %}
        <div class="fw-bold">{{key}}</div>
    {% for value in value_list %}
        <div>
          <li>{{value}}</li>
        </div>
    {% endfor %}
{% endfor %}

rendered html

模型。py:

class Ingredient(models.Model):
    name = models.CharField(max_length=220)
    category = models.CharField(max_length=50, default="uncategorised")

class Shopping(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    name = models.CharField(max_length=220, blank=True, null=True) # users can create their own items not just those in the Ingredient model
    category = models.CharField(max_length=80, default="uncategorised")

意见。py:

def shopping_list_view(request):
    queryset = Shopping.objects.filter(user=request.user)
    shoppingList = {}
            
    for item in queryset:
        
        ingredientItem = item.name # e.g Fish

        ingredientCategory = item.category # e.g. Meat & Seafood

        if ingredientCategory in shoppingList:
            shoppingLists[ingredientCategory].append(ingredientItem)
        else:
            shoppingLists[ingredientCategory] = []
            shoppingLists[ingredientCategory].append(ingredientItem)
    # print(shoppingLists)
    # will return something like > {'Meat & Seafood': ['bacon', 'fish'], 'Baking & Spices': ['all purpose flour', 'parsley'], 'pantry': ['pasta']}
    return render(request, "shopping/shoppinglist.html", {"shoppingList": shoppingList}
    )
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/129358
 
1576 次点击  
文章 [ 1 ]  |  最新文章 3 年前