Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/344.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 根据django类别获取数据_Python_Django_Python 3.x - Fatal编程技术网

Python 根据django类别获取数据

Python 根据django类别获取数据,python,django,python-3.x,Python,Django,Python 3.x,(任何建议都将不胜感激)我有这样的文章范本 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.Decimal

(任何建议都将不胜感激)我有这样的文章范本

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)
现在我想以一种类似“每个类别都有数据库中对象形式的所有文章”的形式获取数据

例如,我有两篇文章,第一篇是“Article 1 having cat1”,第二篇是“Article 2 having cat2”,现在我想得到这样的数据
数据:[cat1:[{Article 1},{}],cat2:[{Article 2}]]
在django有类似的东西吗??到目前为止,我已经尝试过这个代码

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)

假设您的类别模型有一个名称字段。 实际上,您可以循环浏览类别,并使用

def索引(请求,类别\u slug=None):
类别=无
categories=Category.objects.all()
articles=Article.objects.all()
如果为类_段塞:
类别=获取对象或404(类别,段塞=类别段塞)
文章=文章.过滤器(类别=类别)
上下文={
"文章":文章,,
“类别”:类别,
“类别”:类别,

}
如果我理解正确,您需要所有类别以及属于每个类别的所有文章。像这样的
{'cat1':[article1,article2],'cat2':[article4,article5]}
是正确的吗?@binitsing是的exactly@BinitSingh我说不出话来this@BinitSingh你能检查一下吗?实际上这是一个小问题,我得到的只是订单id,在此基础上我可以得到文章,现在每一篇文章都有分类。我正在查询我从哪里获得订购物品order\u article=OrderArticle.objects.filter(order\u order\u number=id,order\u restaurant=restid)兄弟让我检查一下谢谢兄弟。现在我有了准确的数据,但是为什么序列化不接受这个呢?并给出错误“TypeError:“OrderArticle”对象不可编辑“@gamer Great”。请接受答案。序列化问题解决了吗?
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()