Home > OS >  Can't query Many-to-Many relationship in Django
Can't query Many-to-Many relationship in Django

Time:10-06

I do have a Model UserCategoryFilter with a M2M relation to Model Category

# View

@require_GET
def get_category_filter(request):

    # Get the existing user instance if any
    filter_instance = UserCategoryFilter.objects.get(user=request.user)

    # Get the current selections/filters
    selection = filter_instance.categories_selected
    print(selection)

    # Get the form instance and pre-populate it with initial choices
    category_filter_form = SelectCategoryForm(initial={
        'selection': selection,
    })

    # Create the context
    context = {
        'category_filter_form': category_filter_form
    }

    # Render the form instance as string for async DOM population
    template = render_to_string('core/filter_form.html', context=context)

    # Return the string to feed the ajax success function
    return JsonResponse({"form": template})

However, selection always returns None instead of a queryset even though there are three categories selected by the user and stored in the DB. And how to make the form take the initial values from selection?

# Models

class Category(models.Model):

    category = models.CharField(max_length=30)
    category_color = models.CharField(max_length=15, blank=True)

    def __str__(self):
        return str(self.category)


class UserCategoryFilter(models.Model):

    user = models.ForeignKey(Account, on_delete=models.CASCADE)
    categories_selected = models.ManyToManyField(Category)
# 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)

CodePudding user response:

to get them you can use .all().try this

   @require_GET
    def get_category_filter(request):
    
        # Get the existing user instance if any
        filter_instance = UserCategoryFilter.objects.get(user=request.user)
    
        # Get the current selections/filters
        selection = filter_instance.categories_selected.all() #new
        print(selection)

you can also do something like this

   @require_GET
    def get_category_filter(request):
    
        # Get the current selections/filters
        selection = UserCategoryFilter.objects.filter(user=request.user).values_list('categories_selected') #new
        print(selection)
  • Related