Как пофиксить Direct assignment to the forward side of a many-to-many set is prohibited. Use producer.set() instead?
Раньше выдавало ValueError: Cannot assign "'Puzzle'": "Movie.own_genre" must be a "OwnGenre" instance. к таблице OwnGenre, смог пофиксить, вынеся в setUp() в тестах (там был ForeignKey)
tests.py
class MovieSerializerTestCase(TestCase):
def setUp(self):
self.own_genre = OwnGenre.objects.create(name='Puzzle')
self.producer = Producer(name='David Eyre')
def test_serializer(self):
movie = Movie.objects.create(title='Fury', poster=None, year_issue='2014', duration='134',
description='Fury description', producer=self.producer, genre='Drama',
own_genre=self.own_genre, country='USA', film=None)
models.py
class Movie(models.Model):
producer = models.ManyToManyField("Producer")
class Producer(models.Model):
name = models.CharField(max_length=32, unique=True)
slug = models.SlugField(blank=True)
def __str__(self):
return self.name
def get_url(self):
return reverse('movies:producer-detail', args=[self.slug])
def save(self, *args, **kwargs):
self.slug = slugify(self.name)
super(Producer, self).save(*args, **kwargs)
serializers.py
class MovieSerializer(ModelSerializer):
class Meta:
model = Movie
fields = ['title', 'poster', 'year_issue', 'duration', 'description', 'producer', 'genre', 'own_genre',
'country', 'film']
traceback
Traceback (most recent call last):
File "G:\Важное\Сохранения\Django-Projects\reeltime\movies\tests\test_serializers.py", line 18, in test_serializer
movie = Movie.objects.create(title='Fury', poster=None, year_issue='2014', duration='134',
File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\query.py", line 669, in create
obj = self.model(**kwargs)
File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\base.py", line 562, in __init__
_setattr(self, prop, value)
File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\fields\related_descriptors.py", line 597, in __set__
raise TypeError(
TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use producer.set() instead.