Get data on basis of Categories django

438 Views Asked by At

(Any suggestion would be highly appreciated) I have model of Articles like

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)

Now I want to get data in a form like "Every Category will have all articles in form of objects from database"

for example I have 2 articles , 1 is "article1 having cat1" and 2nd "article2 having cat2" Now I want to get data like this data:[ cat1:[{article1},{}] , cat2:[{article2}] ] is there any group by categories like thing in django ?? till now I have tried this code

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

There are 2 best solutions below

4
On BEST ANSWER

Assuming your Categories model has a name field. You can actually loop over categories and get all related articles using related object reference

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()
0
On

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,
    }

Then in your view

{% regroup articles by category as articles_by_category %}
  {% for c in products_by_category %}
  
  {% endfor %}