How to order django rest framework queryset from serializer field? -
how can order django queryset
serializer field? since field complicated, couldn't order queryset
using annotate
, cannot store value in model well.
edit:
serializer
class drinklistmodelserializer(serializers.modelserializer): count_need = serializers.serializermethodfield() url = drink_detail_url class meta: model = drink fields = [ 'name', 'count_need', 'thumbnail', 'url' ] def get_count_need(self, obj): drink_ingredient_qs = obj.ingredients.all() user = self.context['request'].user user_qs = user.objects.filter(username=user.username) if user_qs.exists() , user_qs.count() == 1: user_obj = user_qs.first() user_ingredient_qs = user_obj.ingredient_set.all() return (user_ingredient_qs & drink_ingredient_qs).count() return 0
models:
class drink(models.model): name = models.charfield(max_length = 1000, null=true, blank=true) ingredients = models.manytomanyfield(ingredient, blank=true) user = models.manytomanyfield(settings.auth_user_model, blank=true) class ingredient(models.model): name = models.charfield(max_length = 1000) ingredient_category = models.foreignkey(category, null=true, blank=true) slug = models.slugfield(max_length=255, unique=true) user = models.manytomanyfield(settings.auth_user_model, blank=true)
view
class drinklistapiview(listapiview): serializer_class = drinklistmodelserializer pagination_class = largeresultssetpagination permission_classes = [allowany] def get_queryset(self, *args, **kwargs): user = self.request.user qs = drink.objects.all() userquery = self.request.get.get('user') query = self.request.get.get("q") filters = self.request.get.getlist('filter') if query: qs = qs.filter(name__icontains=query) elif filters: qs = qs.filter(playlist__name__iexact=filters[0]) filter in filters[1:]: qs = qs | drink.objects.filter(playlist__name__iexact=filter) elif userquery , user.is_authenticated(): qs = qs.filter(user=user) return qs.order_by('-timestamp')
currently, i'm ordering queryset timestamp since in model self, need order 'count_need' part of serializer. tried qs = qs.annotate(count_need=count('ingredients' & user_ingredient_qs)).order_by(count_need)
doesnt work since 'ingredients' string here , not drink's ingredient queryset.
one way might work implement , customize to_representation
on list serializer:
def to_representation(self, data): iterable = data.all() if isinstance(data, models.manager) else data iterable = sorted(iterable, key=lambda x: x.count_need) return [ self.child.to_representation(item) item in iterable ]
Comments
Post a Comment