Reputation: 45
Hello Guy I'm a newbie to Django. Im using Rest API with Django to interact with my android application. I have the data I need in variable quest. Since there are multiple questions I'm using filter instead of get.
This is my Views.py:
class MapertablesViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows groups to be viewed or edited.
"""
queryset = Mapertables.objects.all()
serializer_class = MapertablesSerializer
lookup_field = 'category_id'
def get_queryset(self):
#print self.kwargs['category_id']
maps = Mapertables.objects.filter(category_id=self.kwargs['category_id'])
#queryset = list(maps)
#queryset = serializers.serialize('json',maps)
#print "AAAA ",queryset
i = 0
#quest ={}
queryset = []
queslist = []
for question in maps:
quest = {}
quest['question'] = question.question_id
#print 'qqqq ',question.question_id
#queryset = serializers.serialize('json',[question,])
choices = Choice.objects.filter(question=question.question_id)
print choices
#aaa = chain(question,choices)
#print aaa
#queryset = serializers.serialize('json',[question,choices,])
j = 0
for option in choices:
quest[j] = option.choice_text
j += 1
print 'data Here ',quest
#data Here {0: u'Highbury', 1: u'Selhurst Park', 2: u'The Dell', 3: u'Old Trafford', 'question': <Question: At which ground did Eric Cantona commit his "Kung Fu" kick ?>}
serializer_class = CoustomeSerializer(queryset, many=True)
print serializer_class.data
#[]
json = JSONRenderer().render(serializer_class.data)
print 'JSON',json
#[]
i += 1
queryset = queslist
serializer_class = CoustomeSerializer(queryset,many=True)
return queryset
#print "questions",queslist
#print "Ser ",ser.data
This is my serializers.py:
class MapertablesSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Mapertables
fields = ('question_id','category_id')
class CoustomeSerializer(serializers.HyperlinkedModelSerializer):
#questions = MapertablesSerializer(source='question_id')
#choices = ChoiceSerializer(source='choice_text')
class Meta:
model = Question,Choice,Category
fields = ('choice_text','choice_text','choice_text','choice_text','question_id')
URL that is defined to show: http://127.0.0.1:8000/mapers/ Exception Type: KeyError Exception Value: 'category_id'
when I query for a specific category it returns: http://127.0.0.1:8000/mapers/2/ { "detail": "Not found." }
Model.py file is as follows:
from django.db import models
# Create your models here.
class Category(models.Model):
category_name = models.CharField(max_length=200,default='1')
def __str__(self):
return self.category_name
class Question(models.Model):
question_text = models.CharField(max_length=200)
#category_name = models.ForeignKey(Category)
pub_date = models.DateTimeField('date published')
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
was_published_recently.admin_order_field = 'pub_date'
was_published_recently.boolean = True
was_published_recently.short_description = 'Published recently?'
def __str__(self):
return self.question_text
class Mapertables(models.Model):
category_id = models.ForeignKey(Category)
question_id = models.ForeignKey(Question)
class Choice(models.Model):
question = models.ForeignKey(Question)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __str__(self):
return self.choice_text
I want to get all questions related to category and there choices form the choices module that why all the stuff in get_queryset.
Please tell me how to get all the data required for me in MapertablesViewSet class
Thank You in advance if you want me to send the complete project just let me know and I will make zip and upload it to a drive or something.
Upvotes: 3
Views: 3161
Reputation: 2359
@Kevin Brown is right you shouldn't worry about the serializers, or rendering anything on the get_queryset
method, but a thing I noticed in your get_queryset
method is that you don't append any item to the lists queryset
, and querylist
. I'm giving you an idea below:
def get_queryset(self):
#print self.kwargs['category_id']
maps = Mapertables.objects.filter(category_id=self.kwargs['category_id'])
i = 0
queryset = []
for question in maps:
quest = {}
quest['question'] = question.question_id
choices = Choice.objects.filter(question=question.question_id)
print choices
j = 0
for option in choices:
quest[j] = option.choice_text
j += 1
print 'data Here ',quest
# Adding items to queryset list
queryset.append(quest)
i += 1
# You should have values here on queryset list
print queryset
return queryset
As to the URL, be sure you are passing the category_id
as a parameter on the URL pattern. Something like url(r'^mapers/(?P<category_id>\d+)/?'
, if you are not using routers
for this. It would be good if you paste here your URLs definition. Well, I hope it helps you to have a better idea how to continue.
Upvotes: 1
Reputation: 41671
You are returning an empty list from your get_queryset
method, so no objects are being returned in the list view and a specific object cannot be retrieved by the pk
.
You appear to be doing a lot of unrelated things in your get_queryset
method, and they are probably contributing to this issue. You shouldn't be doing any serialization there, DRF will handle that for you later. And you should be doing filtering in the filter_queryset
method, or passing that off to DRF to do. You also can't return any responses from that method, only a queryset.
Upvotes: 0