为了账号安全,请及时绑定邮箱和手机立即绑定

根据类别 django 获取数据

根据类别 django 获取数据

青春有我 2022-07-12 10:24:37
(任何建议将不胜感激)我有文章的模型,如class Articles(models.Model):    restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE , blank=True, null=True)    articlename = models.CharField(max_length=50, null=False, blank=False)    price = models.DecimalField(max_digits=10, decimal_places=2)    category = models.ForeignKey(Categories, on_delete=models.CASCADE , blank=True, null=True)现在我想以“每个类别都将以数据库对象形式的所有文章”之类的形式获取数据例如我有 2 篇文章,1 篇是“article1 有 cat1”,第二篇是“article2 有 cat2” 现在我想获取这样的数据 在 djangodata:[ cat1:[{article1},{}] , cat2:[{article2}] ] 中有没有类似的东西?group by categories直到现在我已经尝试过这段代码order_article = OrderArticle.objects.filter(order__order_number=id ,order__restaurant=restid)         samearticle=[]        for order_obj in order_article:            if : #will check if article having cat already been created                category={}                category[order_obj.article.category.name]=order_obj                samearticle.append(order_obj.article.category.name)            else:                samearticle[order_obj.article.category.name].append(order_obj)
查看完整描述

2 回答

?
沧海一幻觉

TA贡献1824条经验 获得超5个赞

假设您的 Categories 模型有一个名称字段。您实际上可以遍历类别并使用相关对象引用获取所有相关文章


order_article_list = OrderArticle.objects.filter(order__order_number=id ,order__restaurant=restid) 

data = {}

for order_article in order_article_list:

  data[order_article.article.category.name] = order_article.article.category.articles_set.all()


查看完整回答
反对 回复 2022-07-12
?
德玛西亚99

TA贡献1770条经验 获得超3个赞

def index(request, category_slug=None):

    category = None

    categories = Category.objects.all()

    articles = Article.objects.all()

    if category_slug:

        category = get_object_or_404(Category, slug=category_slug)

        articles = articles.filter(category=categories)

    context = {

        'articles': articles,

        'categories': categories,

        'category': category,

    }

那么在你看来


{% regroup articles by category as articles_by_category %}

  {% for c in products_by_category %}

  

  {% endfor %}


查看完整回答
反对 回复 2022-07-12
  • 2 回答
  • 0 关注
  • 127 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号