Can you optimize this code? (Django, python)

后端 未结 2 641
醉话见心
醉话见心 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: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.

提交回复
热议问题