过滤多个对象并在Serializer中返回“new field”

时间:2017-09-20 08:06:05

标签: django django-models django-forms django-rest-framework django-views

youtube capture

就像Youtube一样,我希望看到我的帖子(装备)的类别

我的方法是......

  1. 获取属于用户的整个类别列表
  2. 获取属于用户和帖子的完整类别列表
  3. 比较它们并返回JSON
  4. 在建造一个Seriailizer的同时,我觉得我完全是股票。如此令人沮丧...... :(

    如果您有任何更好的想法,请随时改变我的方法。

    预期的JSON输出位于

    之下
    {
        ...
        "categories": [
        {
            "id": 1,
            "name": "asd"
            "added": True <- since the post is added to 'asd'
        },
        {
            "id": 2,
            "name": "workout"
            "added": True
        }, 
        ...
        {
            "id": 5,
            "name": "bgm"
            "added": False <- since the post is not added to 'bgm'
        }, 
        ]
    }
    

    这是views.py

    class OutfitDetailView(generics.RetrieveAPIView):
        queryset = Outfit.objects.all()
        serializer_class = OutfitDetailSerializer
        lookup_field = 'pk'
    

    这是serializers.py(这是一个问题)

    class OutfitDetailSerializer(serializers.ModelSerializer):
         ...
       def get_categories(self, obj):
                # Right Here! Get whole categories associated with user
                all_categories = Category.objects.filter(owner=self.context['request'].user)
                # And the categories associated with user AND the post
                categories = obj.categories.filter(owner=self.context['request'].user)
    
                return CategorySerializer(categories, many=True).data
    
    class CategorySerializer(serializers.ModelSerializer):    
        class Meta:
            model = Category
            fields = (
                'id',
                'name',
                'added' <- here I want to add 'added' field but I don't know how.
            )
    

    如果您需要型号

    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)
        ...
    

1 个答案:

答案 0 :(得分:1)

如果我理解你的错误,你可以尝试:

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

请注意values您需要添加CategorySerializer

所需的所有字段
class CategorySerializer(serializers.ModelSerializer):
    added = serializers.BooleanField()
    class Meta:
        model = Category
        fields = (
            'id',
            'name',
            'added'
        )