Hello Guy我是Django的新手。我使用Rest API与Django与我的Android应用程序进行交互。 我有变量任务所需的数据。由于有多个问题我使用过滤器而不是get。
这是我的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
这是我的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')
定义为显示的网址: http://127.0.0.1:8000/mapers/ 异常类型:KeyError 例外值:'category_id'
当我查询特定类别时,它返回: http://127.0.0.1:8000/mapers/2/ { “细节”:“没找到。” }
Model.py文件如下:
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
我想获得与类别相关的所有问题,并且选择模块中的选项可以解释为什么get_queryset中的所有内容。
请告诉我如何在MapertablesViewSet类中获取我所需的所有数据
如果您希望我发送完整项目,请提前告知我,我会提前打印并将其上传到驱动器或其他内容。
答案 0 :(得分:1)
@Kevin Brown是对的你不应该担心序列化程序,或者在get_queryset
方法上渲染任何内容,但我在get_queryset
方法中注意到的一点是你不附加任何项目到列表queryset
和querylist
。我在下面给你一个想法:
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
对于URL,请确保将category_id
作为参数传递给URL模式。类似于url(r'^mapers/(?P<category_id>\d+)/?'
的内容,如果你没有使用routers
。如果您在此处粘贴您的网址定义,那就太棒了。好吧,我希望它可以帮助你更好地了解如何继续。
答案 1 :(得分:0)
您正在从get_queryset
方法返回一个空列表,因此列表视图中没有返回任何对象,pk
无法检索到特定对象。
您似乎在get_queryset
方法中做了很多不相关的事情,他们可能会对此问题做出贡献。您不应该在那里进行任何序列化,DRF将在以后为您处理。你应该在filter_queryset
方法中进行过滤,或者将其传递给DRF来做。您也无法从该方法返回任何响应,只返回查询集。