I want to display all questions based on subcategory.
This is my code :
models.py
class Subcategory(models.Model):
subcategory_id = models.BigAutoField(primary_key=True)
subcategory = models.CharField(max_length=40)
class Meta:
managed = True
db_table = 'subcategory'
def __str__(self):
return self.subcategory
class Question(models.Model):
question_id = models.BigAutoField(primary_key=True)
subcategory = models.ForeignKey('Subcategory', models.DO_NOTHING, default=None)
question = models.TextField()
answer = models.CharField(max_length=255)
class Meta:
managed = True
db_table = 'question'
def __str__(self):
return self.question
serializers.py
class SubcategorySerializer(serializers.ModelSerializer):
class Meta:
model = Subcategory
fields = ('subcategory_id',
'subcategory')
class QuestionSerializer(serializers.ModelSerializer):
class Meta:
model = Question
fields = ('question_id',
'subcategory',
'question',
'answer')
view.py
@api_view(['GET', 'POST', 'DELETE'])
def question_list(request):
# GET list of question, POST a new question, DELETE all question
if request.method == 'GET':
questions = Question.objects.all()
question = request.GET.get('question', None)
if question is not None:
questions = questions.filter(question__icontains=question)
questions_serializer = QuestionSerializer(questions, many=True)
return JsonResponse(questions_serializer.data, safe=False)
# 'safe=False' for objects serialization
elif request.method == 'POST':
question_data = JSONParser().parse(request)
questions_serializer = QuestionSerializer(data=question_data)
if questions_serializer.is_valid():
questions_serializer.save()
return JsonResponse(questions_serializer.data, status=status.HTTP_201_CREATED)
return JsonResponse(questions_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
elif request.method == 'DELETE':
count = Question.objects.all().delete()
return JsonResponse({'message': '{} Questions were deleted successfully!'.format(count[0])}, status=status.HTTP_204_NO_CONTENT)
/api/subcategory :
[
{
subcategory_id: 1,
subcategory: "Mathematics"
},
{
subcategory_id: 2,
subcategory: "History"
}
]
/api/questions :
[
{
question_id: 1,
subcategory: 1,
question: "10 + 10 = ?",
answer: "20"
},
{
question_id: 2,
subcategory: 1,
question: "50 + 50 = ?",
answer: "100",
},
{
question_id: 3,
subcategory: 2,
question: "Who was the first president of the United States?",
answer: "George Washington",
}
]
From the data above I have 2 subcategories Mathematics and History and have 3 questions based on the subcategory, 2 questions about mathematics and 1 question about history.
How to display in /api/questions only 2 questions about Mathematics?
I’m still a beginner and need a lot of guidance please help.
Advertisement
Answer
Try with this:
subcategory = request.GET.get('subcategory', None)
if subcategory is not None:
questions = questions.filter(subcategory__subcategory__icontains=subcategory)
You’ll have to pass the subcategory string in your URL query parameters:
?subcategory=Mathematics
But if you want it to be filtered all the time with just Mathematics:
questions.filter(subcategory__subcategory='Mathematics')
You could also try to change subcategory field of Subcategory model to just name to represent the Subcategory name.