Yantra Logistics
Yantra Logistics

Reputation: 308

extract manytomany field from a queryset

Models.py

class AllotmentDocket(models.Model):

    sales_order = models.ForeignKey(MaterialRequest, on_delete=models.CASCADE, related_name='allotment_sales')

class MaterialRequest(models.Model):

    kit = models.ForeignKey(Kit, on_delete=models.CASCADE, related_name='kit')
    quantity = models.IntegerField(default=0)

class Kit(models.Model):
    kit_name = models.CharField(max_length=255, default=0)
    components_per_kit = models.IntegerField(default=0)
    product = models.ManyToManyField(Product, related_name='kit_product')

How can I get all the products information through the related AllotmentDocket?

I tried :

def PrintAllotmentDocket(request, pk):
    AlotmentDocket = get_object_or_404(AllotmentDocket, id=pk)

    kit = MaterialRequest.objects.filter(id=AlotmentDocket.sales_order).values('kit')

but this gives an error:

int() argument must be a string, a bytes-like object or a number, not 'MaterialRequest'

Upvotes: 1

Views: 232

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477881

You can filter with

Product.objects.filter(
    kit_product__kit__allotment_sales=pk
)

with pk the primary key of the AllotmentDocket (so the one passed to the view).

Note: the related_name is the name of the relation in reverse, not the relation in the direction in which you define it.

Upvotes: 1

Related Questions