Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

django many to many post update method via rest

class GroupMembershipSerializer(ModelSerializer):
    class Meta:
        model = Membership
        fields = ('person',)

class GroupCreateSerializer(ModelSerializer):
     memberships = GroupMembershipSerializer(many=True, required=False)

    def create(self, validated_data):
        person_data = validated_data.pop('memberships')
        group = Group.objects.create(**validated_data)
        for person in person_data:
            d=dict(person)
            Membership.objects.create(group=group, person=d['person'])
        return group

    def update(self, instance, validated_data):
        person_data = validated_data.pop('memberships')
        for item in validated_data:
            if Group._meta.get_field(item):
                setattr(instance, item, validated_data[item])
        Membership.objects.filter(group=instance).delete()
        for person in person_data:
            d=dict(person)
            Membership.objects.create(group=instance, person=d['person'])
        instance.save()
        return instance

    class Meta:
        model = Group

class GroupCreateModelViewSet(ModelViewSet):
    serializer_class = GroupCreateSerializer
    queryset = Group.objects.all()
Comment

PREVIOUS NEXT
Code Example
Python :: How To Display An Image On A Tkinter Button 
Python :: create pdf in python 
Python :: decimal to binary 
Python :: default python packages 
Python :: Removing Elements from Python Dictionary Using clear() method 
Python :: Python Tkinter CheckButton Widget Syntax 
Python :: print python reverse list 
Python :: get index of first true value numpy 
Python :: Convert csv to dictionary in Python 
Python :: check boolean python 
Python :: how to convert tensorflow 1.15 model to tflite 
Python :: count TRUE in DF 
Python :: assign exec function to variable python 
Python :: np.append 
Python :: python index for all matches 
Python :: Smart Weather Information App Using Python 
Python :: python pyttsx3 
Python :: python regex (d)(?=d1) 
Python :: double underscore methods python 
Python :: get_permissions 
Python :: how to check if digit in int python 
Python :: how to create a new dataframe in python 
Python :: python types 
Python :: list all files in a folder 
Python :: python docstring 
Python :: python alphanum 
Python :: slack notification pytthon 
Python :: Program to Compute LCM Using GCD 
Python :: numpy datatime object 
Python :: how to get list size python 
ADD CONTENT
Topic
Content
Source link
Name
8+6 =