I am working with filters and really like to idea to use and build filter using Prefetch ‘to_attr’ however I am having small issue accessing attribute name directly. So whatever ‘to_attr’ name I am setting for filter I wanted to access it directly without going through full loop.
I might not be using this correctly and there is way around to make it work, but I am wondering if someone guide me and put me into right direction. Here is my code with data model:
class Colour(models.Model):
colour_id = models.AutoField(primary_key=True)
title = models.CharField(max_length=10, null=True, blank=True)
description = models.CharField(max_length=100, null=True, blank=True)
class Product(models.Model):
product_id = models.AutoField(primary_key=True)
sku = models.CharField(max_length=15, null=True, blank=True)
title = models.CharField(max_length=50, null=True, blank=True)
sub_title = models.CharField(max_length=50, null=True, blank=True)
short_desc = models.CharField(max_length=250, null=True, blank=True)
colour = models.ForeignKey(Colour, on_delete=models.CASCADE,
related_name='wkweb.Colour+')
class ProductVariant(models.Model):
variant_id = models.AutoField(primary_key=True)
product_id = models.ForeignKey(Product, on_delete=models.CASCADE,
related_name='wkweb.Product+')
sku = models.CharField(max_length=15, null=True, blank=True)
unit_price = models.DecimalField(max_digits=6, decimal_places=3, null=True, blank=True)
price = models.DecimalField(max_digits=6, decimal_places=3, null=True, blank=True)
qty = models.IntegerField(null=True, blank=True)
product_list = ProductVariant.objects.prefetch_related("product_id")
filter_colour = product_list.filter(Q(product_id__colour=3) | Q(product_id__colour=2))
filter_set = ProductVariant.objects.prefetch_related( \
Prefetch("product_id", queryset=filter_colour, to_attr="colour"),
The filter_set return all the products along with matched colour filtered products when I run following python loop:
for co in filter_set:
if getattr(co, 'colour'):
print(co.colour.price) ### I WANT THIS WITHOUT RUNNING FULL LOOP
print(co.colour)
I really want to access ‘colour’ attribute without running full loop of filter_set.
Thank you for your help in advance.