Excuse me if this may seem like a straightforward question. I have looked for various solutions, but none of them seem to address my specific issue.
I am dealing with a model that has a many-to-many field relationship. Whenever I create a new object through the DRF REST API, the regular fields of the object (model) get saved correctly, but the many-to-many related field remains empty.
This is 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)
And here is 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)
This is 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']
This is my view:
class CustomerCreate(generics.CreateAPIView):
queryset = CustomerProfile.objects.all()
serializer_class = CustomerSerializer
Here is my POST request:
axios({
method: "POST",
url: this.api_base_url + "api/.../customer_create/",
data: {
first_name: 'Tom',
last_name: 'Hardy',
email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dcb2bdb1b99cbbb1bdb5b0f2bfb3b1">[email protected]</a>',
phone: '01234567898',
stores: ['store_name',], // this is the store I want to link the customer to
}
})
Even though an object is created when I make a POST request to this endpoint, the stores
array always ends up being empty.
Outcome:
data:
email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="89e7e8e4ecc9eee4e8e0e5a7eae6e4">[email protected]</a>"
first_name: "Tom"
last_name: "Hardy"
phone: "08038192642"
stores: []
What is the correct way to add the stores in this scenario?