Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - how can i filter a list of objects checking a foreign key attribute?

First of all sorry for my bad English.

I have to filter a query but using a foreign key attribute. I have a WorkOrder model and have other model with the order movements.

this is the model

class OrderMovements(models.Model):
    workorder = models.ForeignKey(
            WorkOrder,
            verbose_name=_('order'),
        )
    status = models.IntegerField(
            choices=FULL_CHOICES,
            default=1,
            verbose_name=_('status'),
        )
    timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)

Well like you see a work order can have a lot of movements, the queryset that i need to make is a query that take the last 10 WorkOrders that have a OrderMovement with status 3 or 4 included in any of the movements of that WorkOrder.

I really don't know how can a make this.

Hope you can understand me.

Thanks!

like image 505
marcosgue Avatar asked Nov 30 '25 11:11

marcosgue


2 Answers

As usual, you start with the model you want to get, and follow the relationships via double underscores.

WorkOrder.objects.order_by('-timestamp').filter(ordermovements__status__in=[3, 4])[:10]
like image 125
Daniel Roseman Avatar answered Dec 03 '25 01:12

Daniel Roseman


First use related_name to easily perform reverse relation look ups

class OrderMovements(models.Model):
    workorder = models.ForeignKey(
        WorkOrder,
        related_name='ordermovements',
        verbose_name=_('order'),
    )
    // rest code

Then you can query workorder and use related_name for reverse relationship filter.

Also you require distinct to avoid duplicates

Your query should be:

WorkOrder.objects.order_by('-timestamp').filter(
    ordermovements__status__in=[3, 4]).distinct('-timestamp')[:10] 
like image 23
Raj Subit Avatar answered Dec 03 '25 02:12

Raj Subit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!