A
A
Aliarystan2019-08-06 18:52:40
Django
Aliarystan, 2019-08-06 18:52:40

How to pull out child objects in Django with one serialize?

There are such models

class Dictionary(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    parentId = models.UUIDField(editable=True, null=True)
    name = models.CharField(max_length=100)
    date_create = models.DateTimeField(auto_now=True)
    date_end = models.DateTimeField(auto_now=False, null=True)


class Teacher(models.Model):
    name = models.CharField(max_length=100)
    message = models.CharField(max_length=300)
    status = models.OneToOneField(Dictionary, on_delete=models.CASCADE)

There is such urls
from django.urls import path
from . import views
urlpatterns = [
    path('get', views.GetViewSet.as_view({'get': 'list'})),
    ]

There is such a ViewSet
class GetViewSet(viewsets.ModelViewSet):
    MyApiObj = null

    @property
    def api_object(self):
        return namedtuple("ApiObject", self.request.data.keys())(*self.request.data.values())

    def get_serializer_class(self):
        GeneralSerializer.Meta.model = apps.get_model(app_label=self.MyApiObj.app,  model_name=self.MyApiObj.object)
        return GeneralSerializer

    def post(self, request):
        self.MyApiObj = self.api_object
        return self.select_api()

    def select_api(self):
        queryset = QueryHelper.select(self.MyApiObj)
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

Serializer like this
class GeneralSerializer(serializers.ModelSerializer):
    class Meta:
        model = None
        fields = '__all__'

Post method I pass such parameters
{  
   "app":"leads",
   "object":"Teacher",
   "settings":{ 
   },
   "data":{  

   }
}

the answer is this
[
    {
        "id": 1,
        "name": "John",
        "message": "Hi everyone",
        "status": "e3b86ed4-8794-413b-994c-b1ec0a43eebe"
    }
]

The problem is that I need to pull out the child class Dictionary (status) in Teacher not id (uuid) but the object itself without creating a separate serializer for dictionary.
tried this and it works
class DictionarySerializer(serializers.ModelSerializer):
    class Meta:
        model = Dictionary
        fields = '__all__'


class GeneralSerializer(serializers.ModelSerializer):
    status = DictionarySerializer(required=True)
    class Meta:
        model = None
        fields = '__all__'

But it will not work because
1 Do not create another serializer
2 Not only for the dictionary model, but it must be universal for all models with child objects
Please help)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
aliarystan, 2019-08-06
@aliarystan

I decided. It is necessary to write depth = 1 in the meta serializer and that's it)))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question