Answer the question
In order to leave comments, you need to log in
How to get a list of defined models in django-rest Serializer?
Good day.
Task: get all objects in another serializer. Clearer in the code:
There is a custom serializer
class TestSerializer(Serializer):
type = PrimaryKeyRelatedField(queryset=Type.objects.all(),many=True)
class Type(models.Model):
id = models.UUIDField(primary_key=True, default=uuid4)
name = models.CharField(null=True, max_length=255)
def __str__(self):
return self.name
class TypeSerializer(ModelSerializer):
class Meta:
model = Type
fields = '__all__'
@api_view(['GET', 'POST'])
def test(request):
if request.method == 'GET':
serializer = TestSerializer()
return Response(serializer.data)
...
{
"type": [],
}
Answer the question
In order to leave comments, you need to log in
1) TypeSerializer
is not called anywhere. How does Django know that you want to use it?
2) See documentation. You need, I think, a nested relationship. www.django-rest-framework.org/api-guide/relations/...
3) serializator
- why such horror? In Russian "serializer". In English "serializer". And nothing else.
4) It is better to leave views as functions immediately and forever. Use class based views.
5) Given that you are using DRF and it provides many classes for this, starting from APIView. And also such convenient things as viewsets and routers.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question