2

I have looked at this submission and there is so much clutter in the code I am having a hard time following it: Pass a custom queryset to serializer in Django Rest Framework

Now currently, I am trying to write a serializer that returns a list of all the cities in my table of venues. There may be many venues in each city, but I only want to return the city name once.

I know I need to create a custom model manager for this to modify the queryset, but I am unsure how to pass it to the serializer. I am rather lost in documentation and example. Do I need to write sql do I not? This is why not having a mentor really is a pain.

what I have so far.

models.py:

  class Venue(models.Model):
    name = models.CharField(max_length=150, blank=False)
    description = models.CharField(max_length=1000)
    image = models.ImageField(upload_to=imgUnique('venueMedia/venueImages'))
    streetAddress= models.CharField(max_length=100)
    city = models.CharField(max_length=100, blank=False)
    state = models.CharField(max_length=100, blank=False)

serializers.py:

from rest_framework import serializers
from models import Venue, Room

class citySerializer(serializers.Serializer):

and my custom model in models.py:

class CityListManager(models.Manager):
def get_query_set(self):
    return super(CityListManager, self).get_query_set().filter

All of the code is incomplete as I figure this out and put it all together

0

1 Answer 1

0

so looks like I was doing it wrong in the first place here is the working code

# queryset for cityListView
def getcityList():

    cityList = Venue.objects.raw("""SELECT  DISTINCT city
                                 FROM Venue""")
    return cityList

class citySerializer(serializers.ModelSerializer):

    class Meta:
        model = Venue
        fields = 'city'
        read_only_fields = 'city'

class cityListViewSet(viewsets.viewSet):

    def list(self, request):
        queryset = getcityList()
        serializer = citySerializer(queryset, many=True)
        return Response(serializer.data)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.