如何根据外键设置标准从Django Rest序列化器中过滤掉对象

时间:2015-05-14 22:02:13

标签: python django django-rest-framework

我正在使用Django Rest Framework,这就是我遇到的问题。

我有3个型号,如下所示。

class Store(models.Model):
    name = models.CharField(unique=True, max_length=255)
    ...
    is_valid = models.IntegerField(default=0)
    ...

class Category(models.Model):
    category = models.CharField(max_length=255, unique=True)
    importance = models.IntegerField(default=0, null=True)


class StoreCategory(models.Model):
    store = models.ForeignKey(Store)
    category = models.ForeignKey(Category)

对于其余框架,这些是我的序列化器:

class StoreCategorySerializer(serializers.ModelSerializer):
    store = StoreSerializer(read_only=True)
    class Meta:
        model = StoreCategory
        fields = ('store', )

class AllStoreSerializer(serializers.ModelSerializer):
    # stores = StoreCategorySerializer(source="storecategory_set", many=True)
    stores = serializers.SerializerMethodField('get_stores_list')

    def get_stores_list(self, obj):
        scs = obj.storecategory_set.exclude(store__is_valid=0).order_by('store__id')
        serializer = StoreCategorySerializer(scs, many=True)
        return serializer.data

    class Meta:
        model = Category
        fields = ('id', 'category', 'stores')

查看如下:

class AllStores(APIView):
    def get(self, request):
        categories = Category.objects.all().order_by('-importance')
        serializer = AllStoreSerializer(categories, many=True)
        return Response(serializer.data)

现在,问题是,我想返回存储有is_valid!= 0的类别。即如果某个类别的商店列表有0个元素,那么该类别不包含在返回的数据中(返回的数据)通过API)。所以基本上id是storecategory_set的大小等于0,然后不包括该类别。 我怎么能这样做?

谢谢:)

0 个答案:

没有答案