Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List Serializer multiple object creation

My models are:

class User(models.Model):
    id = models.AutoField(primary_key=True)
    email = models.EmailField()


class Lawyer(models.Model):    
    user = models.OnetoOneField(User)


class Session(models.Model):
    name = models.CharField()
    lawyer = models.ForeignKey(Lawyer)

I am trying to create multiple objects with a list serializer for Session.
From the app side they don't have the id of lawyer, but have the email of each lawyer. How can I write a list serializer where I can take the following json input and use email to fetch lawyer to store multiple session objects?

The json input sent will be like:

[
    {
        "name": "sess1",
        "email": "[email protected]",
    },
    {
        "name": "sess1",
        "email": "[email protected]",
    }
]
like image 436
Jiss Raphel Avatar asked Jul 09 '26 21:07

Jiss Raphel


1 Answers

You can do it in this way but I think email should be unique=True.

Then use a serializer like this:

from django.utils.translation import ugettext_lazy as _

class SessionCreateManySerializer(serializers.ModelSerializer):
    email = serializers.SlugRelatedField(
        source='lawyer',
        slug_field='user__email',
        queryset=Lawyer.objects.all(),
        write_only=True,
        error_messages={"does_not_exist": _('lawyer with email={value} does not exist.')}
)

    class Meta:
        model = Session
        fields = ('name', 'email')

and a generic create view (just override get_serializer and place many=True in kwargs ):

from rest_framework.response import Response
from rest_framework import generics

class SessionCreateManyView(generics.CreateAPIView):
    serializer_class = SessionCreateManySerializer

    def get_serializer(self, *args, **kwargs):
        kwargs['many'] = True
        return super(SessionCreateManyView, self).get_serializer(*args, **kwargs)
like image 141
Ehsan Nouri Avatar answered Jul 14 '26 06:07

Ehsan Nouri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!