python - How to filter out objects from Django Rest serializer based on Foreign key set criteria -
i'm using django rest framework , got stuck.
i have 3 models, follows.
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)
for rest framework these serializers have:
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')
view follows:
class allstores(apiview): def get(self, request): categories = category.objects.all().order_by('-importance') serializer = allstoreserializer(categories, many=true) return response(serializer.data)
now, problem is, want return categories there stores is_valid != 0. i.e. if stores list category has 0 elements, category not included in data returned(data returned api). id storecategory_set has size equal 0, not include category. how can this?
thanks :)
Comments
Post a Comment