python

Django send post request with different field than primary key.

class ContactCompanySerializer(serializers.ModelSerializer):
    # profile=ProfileSerializer()
    # array şeklinde gönderiyoruz. Array içindekiler de charfield yani string.
    integration_requirements = serializers.ListSerializer(
        child=serializers.CharField())

    class Meta:
        model = ContactCompany
        fields = ('id', 'name', 'website', 'country', 'city',
                  'address', 'sector', 'note', 'profile',
                  'integration_requirements')
        # exclude_fields = ('created_at', 'updated_at', 'is_active')
    
    # create methodunu override ediyoruz.
    def create(self, validated_data):
        # integration requirements kısmını validatet datadan çekiyoruz (array olarak).
        integration_requirements = validated_data.pop(
            'integration_requirements', [])
        # company objemizi oluÅŸturuyoruz ve IntegrationRequirement modelinden
        # post requestte gönderdiğimiz requirementleri filtreliyoruz.
        company = super().create(validated_data)
        integration_requirements_qs = IntegrationRequirement.objects.filter(
            requirement__in=integration_requirements)
        # Company'e direkt olarak requirementsleri ekliyoruz.
        company.integration_requirements.add(*integration_requirements_qs)
        return company
Was this helpful?