Can you optimize this code? (Django, python)

后端 未结 2 625
醉话见心
醉话见心 2021-01-15 17:02

I\'m adding \'added\' field to check which categories User\'s Post(Outfit) is added to. It sounds horrible, so let\'s dive in to the code.

I want to optimize

2条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-15 17:08

    If i get you right, you can get necessary data with django raw sql:

    q = """\
    SELECT yourappname_category.id,
           yourappname_category.name,
           COUNT(outfit_id) > 0 as added 
    FROM yourappname_category
      LEFT JOIN yourappname_category_outfits 
          ON yourappname_category.id = yourappname_category_outfits.category_id 
             AND yourappname_category_outfits.outfit_id=%s
    WHERE yourappname_category.owner_id=%s
    GROUP BY yourappname_category.id, yourappname_category.name"""
    
    categories = Category.objects.raw(q, [obj.id, user.id])
    results = [{'id': c.id, 'name': c.name, 'added': c.added} for c in categories]
    

提交回复
热议问题