+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

暂无数据

从查询集中提取数据

发布于2021-01-17 16:47     阅读(507)     评论(0)     点赞(10)     收藏(0)


0

1

2

3

4

5

6

7

8

9

型号

class MasterItems(models.Model):

    owner = models.ForeignKey(Teacher, on_delete=models.CASCADE, related_name='ShipperItems_owner')
    name = models.CharField(max_length=255, default="", null=True)

    length = models.FloatField(blank=True, null=True)
    breadth = models.FloatField(blank=True, null=True)
    height = models.FloatField(blank=True, null=True)
    weight = models.FloatField(blank=True, null=True)


class SalesOrderItems(models.Model):
    item = models.ForeignKey(MasterItems, on_delete=models.CASCADE)
    item_quantity = models.IntegerField(default=0)


class SalesOrder(models.Model):

    owner = models.ForeignKey(Teacher, on_delete=models.CASCADE, related_name='so_owner')
    client = models.ForeignKey(MasterClient, on_delete=models.CASCADE, related_name='so_client')
    items = models.ManyToManyField(SalesOrderItems, related_name='items_so', blank=True, null=True)

我从前端收到pk例如的销售订单,[4,2]并且我想提取与这些订单相关的项目SalesOrder

我试过的

        items = []

        for i in sales_orders:

            so_items = SalesOrderItems.objects.filter(items_so=i)
            print("so_items ", so_items)

            items.append(so_items)

但是我得到的输出是这样的:

items = [<QuerySet [<SalesOrderItems: SalesOrderItems object (4)>, <SalesOrderItems: SalesOrderItems object (5)>]>, <QuerySet [<SalesOrderItems: SalesOrderItems object (1)>]>]

如何获得物品的重量?实际上,SalesOrderItems具有item_quantity,我想将该数量乘以项目重量,以获得项目的总重量


解决方案


请尝试以下操作:

进行单个查询(可选,这只是一种优化):

queryset = SalesOrderItems.objects.filter(items_so__pk__in=sales_orders)

然后像下面这样乘:

from django.db.models import FloatField, F, ExpressionWrapper

items = queryset.annotate(total_weight=ExpressionWrapper(
    F('item_quantity') * F('item__weight'), output_field=FloatField())

queryset中的每个对象都有一个名为的新属性total_weight,这就是您需要的值。

for item in items:
    item.total_weight # this is what you are looking for

0

1

2

3

4

5



所属网站分类: 技术文章 > 问答

作者:黑洞官方问答小能手

链接: https://www.pythonheidong.com/blog/article/777278/543baf18c6175e906825/

来源: python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

10 0
收藏该文
已收藏

评论内容:(最多支持255个字符)