Can you optimize this code? (Django, python)

后端 未结 2 624
醉话见心
醉话见心 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]
    
    0 讨论(0)
  • 2021-01-15 17:27

    If I understand your use case correctly you just want "to check which categories User's Post(Outfit) is added to". For that you would only need to return the ones with added = true right? and then you could leave the added key out.

    as in:

    "categories": [{
            "id": 1,
            "name": "Gym"
        }, {
            "id": 3,
            "name": "hollymo"
        }
    ]
    

    If so, you could just use:

    import Category from category.models
    
    class CategoriesSerializer(serializers.ModelSerializer):
    
        class Meta:
            model = Category
            fields = ('id', 'name')
    
    class OutfitDetailSerializer(serializers.ModelSerializer):
        categories = CategoriesSerializer(many=True)
    

    If instead your use case is to show a list of all categories and then do something with just the ones that the current outfit is added to, I'd suggest doing 2 API calls instead of your current logic; One with the answer I supplied above and one to get all categories. Then do that 'added' logic in your front-end as its presentation layer logic imo.

    I'd certainly try to avoid doing raw SQL queries in Django, it cuts the purpose of migrations and is rarely necessary.

    0 讨论(0)
提交回复
热议问题