A
A
Andrey Kovalchuk2017-05-30 09:21:56
Django
Andrey Kovalchuk, 2017-05-30 09:21:56

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)

There is this model:
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

And there is its serializer:
class TypeSerializer(ModelSerializer):
    class Meta:
        model = Type
        fields = '__all__'

Two objects of the corresponding model are created in the database.
Output code:
@api_view(['GET', 'POST'])
def test(request):
    if request.method == 'GET':
        serializer = TestSerializer()
        return Response(serializer.data)
...

At the output I get:
{
  "type": [],
}

The question is why these two records are not displayed from the database?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anatoly Scherbakov, 2017-05-30
@Altaisoft

1) TypeSerializeris 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 question

Ask a Question

731 491 924 answers to any question