Django 1.11 禁止直接赋值给多对多集合的前端

Django 1.11 Direct assignment to the forward side of a many-to-many set is prohibited

我有一个 UserSong 模型,它有两个带有模型流派和语言的 m2m 字段

class UserSong(models.Model):
    title           = models.CharField(max_length=100)
    song_file       = models.FileField(upload_to=user_song_directory_path, validators=[validate_audio_file_extension])
    genre           = models.ManyToManyField(Genre)
    language        = models.ManyToManyField(Language)

类型class是

class Genre(models.Model):
    name            = models.CharField(max_length=255)
    created_date    = models.DateTimeField(auto_now_add=True)
    updated_date    = models.DateTimeField(auto_now=True)
    status          = models.BooleanField(default=False)

语言class是

class Language(models.Model):
    name            = models.CharField(max_length=255)
    created_date    = models.DateTimeField(auto_now_add=True)
    updated_date    = models.DateTimeField(auto_now=True)
    status          = models.BooleanField(default=False)

我正尝试在 UserSong 对象中添加 m2m 字段作为

genre_name_list =  Genre.objects.filter(name__in=self.cleaned_data['genre'].values_list('name',flat=True))
        # instance.genre.add(*genre_name_list)
        instance.genre.set(genre_name_list)

language_name_list =  Language.objects.filter(name__in=self.cleaned_data['language'].values_list('name',flat=True))
        # instance.language.add(*language_name_list)
        instance.language.set(language_name_list)

这里的问题是,m2m table 正在更新,但 Django 仍然给我错误 Direct assignment to the forward side of a many-to-many set is prohibited. Use language.set() instead.

堆栈跟踪

form.cleaned_data['genre'] <class 'genre.models.Genre'>
artist received is  <QuerySet [<UserProfile: Pragya Nagpal>]>
Internal Server Error: /users/5/25/edit_music
Traceback (most recent call last):
  File "/usr/lib/python3.5/site-packages/django/core/handlers/exception.py", line 35, in inner
    response = get_response(request)
  File "/usr/lib/python3.5/site-packages/django/core/handlers/base.py", line 128, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/usr/lib/python3.5/site-packages/django/core/handlers/base.py", line 126, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/usr/lib/python3.5/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "/usr/lib/python3.5/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "/root/new_songdew_store/songdewUser/views.py", line 833, in add_edit_music
    status=model_instance.status)
  File "/usr/lib/python3.5/site-packages/django/db/models/manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/usr/lib/python3.5/site-packages/django/db/models/query.py", line 415, in create
    obj = self.model(**kwargs)
  File "/usr/lib/python3.5/site-packages/django/db/models/base.py", line 490, in __init__
    _setattr(self, prop, kwargs[prop])
  File "/usr/lib/python3.5/site-packages/django/db/models/fields/related_descriptors.py", line 509, in __set__
    % self._get_set_deprecation_msg_params(),
TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use language.set() instead.

回溯显示错误发生在 product_item = Product.objects.create() 调用中。您需要先创建实例,然后为任何多对多字段设置值:

product_item = Product.objects.create(...)
product_item.genre.set(...)