Using Django 2.2 and Postgres database. I'm supposed to show a product page, where someone chooses product attributes and then the view fetches the product variant based on the attributes. When I run a double filter based on two ManytoMany attributes in shell it works fine and returns the single product variant, but when it is run by the view the second filter is ignored and it returns multiple.

I've tried this on both my machine (manage.py runserver / shell) and in the production environment (gunicorn vs shell). I've tried to filter by multiple methods, and second filter is always ignored.

models.py relevant data

class VariantType(models.Model):
    name = models.CharField(max_length=200, db_index=True)

class VariantValue(models.Model):
    name = models.CharField(max_length=200, db_index=True)
    var_type = models.ForeignKey(VariantType, related_name='value', on_delete=models.PROTECT)

class Product(models.Model):
    (info fields for product)

class VariantProduct(models.Model):
    master = models.ForeignKey(Product, related_name='variants', on_delete=models.PROTECT)
    variant = models.ManyToManyField(VariantValue, related_name='products')
    (info fields for VariantProduct)

views.py

@require_POST
def var_manage(request, product_id):
    data = request.POST
    sizevar = VariantValue.objects.get(id=data.get('size')[0])
    colorvar = VariantValue.objects.get(id=data.get('colour')[0])
    product = get_object_or_404(Product, id=product_id)
    var_product = product.variants.filter(master=product, variant=sizevar).filter(variant=colorvar)
    (further action with var_product)

manage.py shell

#set POST data manuall
data = {'csrfmiddlewaretoken': ['...'], 'size': ['18'], 'colour': ['13'], 'items': ['1']};
sizevar = VariantValue.objects.get(id=data.get('size')[0]);
colorvar = VariantValue.objects.get(id=data.get('colour')[0]);
product = get_object_or_404(Product, id=product_id);
var_product = product.variants.filter(master=product, variant=sizevar).filter(variant=colorvar);

if I print or fetch var_product from the server in any way it returns multiple results equal to the result of the first filter, but in shell var_product returns the correct amount for the duplicated code (a single entry).

I'm really struggling to see where my error is, or why it's behaving differently.

0 Answers