简体   繁体   English

基于外键的Django过滤

[英]django filtering based on foreign key

I need to get all the orders except orders with order_type =14 (order table has a foreign key reference to order_type and batch tables) when i am calling the url. 当我调用url时,我需要获取除order_type = 14的订单以外的所有订单(订单表具有对order_type和批处理表的外键引用)。 Please help me to know the solution. 请帮助我了解解决方案。

#models.py

class Batch(models.Model):
        batchnum = models.TextField(null=True, blank=True)
        otp= models.TextField(null=True, blank=True)

class Order(models.Model):
    reqnum = models.TextField(null=True, blank=True)
    order_date = models.DateField(auto_now_add=True, null=True, blank=True)
    batch= models.ForeignKey(Batch, db_index=True,related_name='results', on_delete=models.PROTECT,null=True, blank=True)
    order_status = models.ForeignKey('DotOrderStatus', on_delete=models.SET_NULL, null=True,related_name='dot_order_status',default=1)
    order_type = models.ForeignKey('DotOrderType', on_delete=models.SET_NULL, null=True,related_name='dot_order_type',default=10)
    slno = models.TextField(null=True, blank=True)
    customer_name = models.TextField(null=True, blank=True)
    contact = models.BigIntegerField( null=True, blank=True)


url:localhost:8000/api/v1/batch/id 

where '/id' is batch id 其中'/ id'是批次ID

Please help me to know the solution. 请帮助我了解解决方案。

Thanks in advance. 提前致谢。

You can use exclude in order not to include the order with ID 14: 您可以使用exclude以不包括ID为14的订单:

batch_orders = batch.results.all().exclude(order_type__id=14)

Hope it helps. 希望能帮助到你。

使用exclude排除order_type id 14,并使用filter按批次ID进行过滤

Order.objects.exclude(order_type__id=14).filter(batch__id=id)

您可以这样进行。

Order.objects.filter(batch_id=id).exclude(order_type_id=14)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM