将查询集分配给 Django 中的 M2M 字段会导致“'ManyRelatedManager' 对象没有属性 'category'”

Assigning a queryset to a M2M field in Django results in "'ManyRelatedManager' object has no attribute 'category'"

# View

@require_POST
def update_category_filter(request):
    """
    Updates the Category filter
    """
    # User logged in?
    if request.user.is_authenticated:

        # Get the form instance
        filter_form = SelectCategoryForm(request.POST)

        # Form validation
        if filter_form.is_valid():

            # Check if user already has a filter instance
            instance_exists = UserCategoryFilter.objects.filter(user=request.user)

            # Get the cleaned data
            selection = filter_form.clean()
            list(selection)
            print(selection)

            # If not create, else update
            if not instance_exists:
                filter_instance = UserCategoryFilter.objects.create(user=request.user)
                print(filter_instance)

                # Add each selected filter of queryset to model instance
                for member in selection:
                    filter_instance.categories_selected.category.add(member)    # breaks here 

selection 是一个干净的查询集,我想用它来填充多对多字段。然而,这导致

'ManyRelatedManager' object has no attribute 'category'

# Model

class UserCategoryFilter(models.Model):
    """
    Saves the selected category filter by a user
    """
    user = models.ForeignKey(Account, on_delete=models.CASCADE)
    categories_selected = models.ManyToManyField(Category)

class Category(models.Model):
    """
    Model to define categories and their color styles
    """
    category = models.CharField(max_length=30)
# Form

class SelectCategoryForm(forms.Form):
    """
    A form to update category filters for logged in users
    """
    choices = forms.ModelMultipleChoiceField(queryset=Category.objects.all().order_by('category'),
                                             widget=forms.CheckboxSelectMultiple)

如错误所示,categories_selected 是经理,因此要添加一个类别,它应该只是:

for member in selection['choices']:
    filter_instance.categories_selected.add(member)

或者不循环执行:

filter_instance.categories_selected.add(*selection['choices'])

但这仅在 selectionCategory 个对象的列表时有效。