Hi. I'm trying to save a data to a many-to-many field, but I'm getting this error Direct assignment to the forward side of a many-to-many set is prohibited. Use can_be_used_in_airport.set() instead.
I'm using Django REST Framework and a Vue frontend. From the frontend, I send only the airport and card IDs and then get their instances and save them in the backend.
class CardProgramme(models.Model):
...
can_be_used_in_airport = models.ManyToManyField(to=Airport)
card = models.ManyToManyField(Card)
This is my CardProgrammeSerializer class:
class CardProgrammeSerializer(serializers.ModelSerializer):
can_be_used_in_airport = AirportSerializer(read_only=True, many=True)
card = CardSerializer(read_only=True, many=True)
def create(self, validated_data):
airport_ids = self.context['request'].data['can_be_used_in_airport']
card_ids = self.context['request'].data['card']
cardProgramme = CardProgramme.objects.create(
programme_name=validated_data['programme_name'],
monthly_lounges=validated_data['monthly_lounges'],
quarterly_lounges=validated_data['quarterly_lounges'],
half_yearly_lounges=validated_data['half_yearly_lounges'],
yearly_lounges=validated_data['yearly_lounges'],
programme_start_date=validated_data['programme_start_date'],
programme_end_date=validated_data['programme_end_date']
)
for airport in airport_ids:
print(airport)
airportModelSet = Airport.objects.filter(pk=airport)
print(airportModelSet)
cardProgramme.can_be_used_in_airport=(airportModelSet)
# cardProgramme.save()
return True
but when I use that, it throws another error
Field 'id' expected a number but got ','.