alkadelik
alkadelik

Reputation: 573

Save many-to-many field on object create - Django DRF

Pardon me if this is an obvious question. I've searched different answers but they don't answer my specific case.

I have a model that has a many-to-many field relationship. When I create a new object via DRF rest API, the normal fields of the object (model) are saved correctly but the many-to-many related field remains empty.

My model with the many-to-many related field:

class CustomerProfile(models.Model):
    ...
    stores = models.ManyToManyField(Store) # <- the related field
    first_name = models.CharField(max_length=30, blank=True)
    last_name = models.CharField(max_length=30, blank=True)
    email = models.EmailField(max_length=60, blank=True)
    phone = models.CharField(max_length=15, blank=True)

    def __str__(self):
        return str(self.first_name)

The related (store) model:

class Store(models.Model):
    store_name = models.CharField(max_length=30, unique=True, null=True)
    ...
    
    def __str__(self):
        return str(self.store_name)

My serializer:

class CustomerSerializer(serializers.ModelSerializer):
    stores = StoreSerializer(read_only=True, many=True)

    class Meta:
        model = CustomerProfile
        fields = ['stores', 'first_name', 'last_name', 'email', 'phone']

My view:

class CustomerCreate(generics.CreateAPIView):
    queryset = CustomerProfile.objects.all()
    serializer_class = CustomerSerializer

My post:

axios({
    method: "POST",
    url: this.api_base_url + "api/.../customer_create/",
    data: {
        first_name: 'Tom',
        last_name: 'Hardy',
        email: '[email protected]',
        phone: '01234567898',
        stores: ['store_name',], // this is the store I want to link the customer to
    }
})

When I post to this endpoint, an object is created but the stores array is always empty.

Results:

data:
  email: "[email protected]"
  first_name: "Tom"
  last_name: "Hardy"
  phone: "08038192642"
  stores: []

What is the right way to add the stores?

Upvotes: 0

Views: 1251

Answers (1)

Siva Sankar
Siva Sankar

Reputation: 1820

class CustomerSerializer(serializers.ModelSerializer):
    stores = serializers.PrimaryKeyRelatedField(queryset=Store.objects.all(), write_only=True,many=True)

    class Meta:
        model = CustomerProfile
        fields = ['stores', 'first_name', 'last_name', 'email', 'phone']

Upvotes: 1

Related Questions