你能优化这段代码吗?(姜戈,蟒蛇) [英] Can you optimize this code? (Django, python)

查看:38
本文介绍了你能优化这段代码吗?(姜戈,蟒蛇)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在添加已添加"字段以检查用户的帖子(服装)添加到哪些类别.这听起来很可怕,所以让我们深入研究代码.

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.

我想优化 get_categories(self, obj) 函数.

class CategorySerializer(serializers.ModelSerializer):
    added = serializers.BooleanField()
    class Meta:
        model = Category
        fields = (
            'id',
            'name',
            'added'
        )


class OutfitDetailSerializer(serializers.ModelSerializer):

    def get_categories(self, obj):
        user = self.context['request'].user
        categories = Category.objects.filter(owner=user)
        added = categories.extra(select={'added': '1'}).filter(outfits__pk=obj.pk)
        added = list(added.values('added', 'name', 'id'))
        added_f = categories.extra(select={'added': '0'}).exclude(outfits__pk=obj.pk)
        added_f = list(added_f.values('added', 'name', 'id'))
        categories = added + added_f
        return CategorySerializer(categories, many=True).data

输出如下!

"categories": [{
        "id": 1,
        "name": "Gym",
        "added": true
    }, {
        "id": 2,
        "name": "School",
        "added": false
    }, {
        "id": 3,
        "name": "hollymo",
        "added": true
    }, {
        "id": 4,
        "name": "Normal",
        "added": false
    }, {
        "id": 6,
        "name": "New Category",
        "added": false
    }
]

这里是models.py

Here is models.py

class Outfit(models.Model):
    ...
    user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True)
    content = models.CharField(max_length=30)
    ...

class Category(models.Model):
    name = models.CharField(max_length=20)
    owner = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True)
    outfits = models.ManyToManyField(Outfit, related_name="categories", blank=True)
    main_img = models.ImageField(
                            upload_to=upload_location_category,
                            null=True,
                            blank=True)
    ...

这里是 repo for test

推荐答案

如果我猜对了,你可以通过 django raw sql:

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]

这篇关于你能优化这段代码吗?(姜戈,蟒蛇)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆