从 Django 查询中的多对多关系中检索项目
Posted
技术标签:
【中文标题】从 Django 查询中的多对多关系中检索项目【英文标题】:Retrieve items from Many-to-Many relationship in Django query 【发布时间】:2020-03-03 05:27:40 【问题描述】:模型.py
class SalesOrderItems(models.Model):
item = models.ForeignKey(MasterItems, on_delete=models.CASCADE)
item_quantity = models.IntegerField(default=0)
class SalesOrder(models.Model):
delivery_method_choice = (('Full-Truck Load', 'Full-Truck Load'), ('Part-Truck Load', 'Part-Truck Load'))
status_choices = (('On Hold', 'On Hold'),('Ready to Dispatch', 'Ready to Dispatch'),('Dispatched', 'Dispatched'))
owner = models.ForeignKey(Teacher, on_delete=models.CASCADE, related_name='so_owner')
client = models.ForeignKey(MasterClient, on_delete=models.CASCADE, related_name='so_client')
reference_no = models.CharField(max_length=500, blank=True, null=True)
date = models.DateField(default=datetime.date.today)
shipment_date = models.DateField(default=datetime.date.today)
delivery_method = models.CharField(max_length=500, default='Full-Truck Load', choices=delivery_method_choice)
items = models.ManyToManyField(SalesOrderItems, related_name='items_so', blank=True, null=True)
status = models.CharField(max_length=500, default='On Hold', choices=status_choices)
origin = models.CharField(max_length=255)
destination = models.CharField(max_length=255)
我想通过 django 查询检索特定销售订单的items
我尝试获取物品:
items = []
for i in sales_orders:
so = SalesOrder.objects.filter(pk=i)[0]
print("items",so.items)
输出:
items clas-s-room.SalesOrderItems.None
如何在特定的SalesOrder
中获取items
的列表??
【问题讨论】:
【参考方案1】:sales_orders = SalesOrder.objects.prefetch_related('items').filter(**sales_filter_here)
for sales_order in sales_orders:
for sales_order_item in sales_order.items.all():
print(sales_order_item)
【讨论】:
【参考方案2】:这个查询对你有用
SalesOrder.objects.filter(id=1).values_list('items__item__item_name')
下面是我的简单 Masteritems 模型
class MasterItems(models.Model):
item_name = models.CharField(max_length=50)
def __str__(self):
return self.item_name
通过这种方式,您将获得查询集中的每个项目名称。这是我的简单输出
<QuerySet [('rice',), ('pepsi',), ('Computer',)]>
【讨论】:
以上是关于从 Django 查询中的多对多关系中检索项目的主要内容,如果未能解决你的问题,请参考以下文章
在 TypeORM 与 GraphQL 的多对多关系上使用数据加载器,查询多对多