django 如何从与字段没有直接关联的表中引用字段?

gfttwv5a  于 2023-03-04  发布在  Go
关注(0)|答案(1)|浏览(179)

在Django ORM中,我尝试加入4个表,订单,订单细节,项目和项目照片,并ItemPhoto.photo从订单表访问www.example.com。
起初,我用从OrderDetail表开始的Subquery编写代码,可以得到我想要得到的字段,但我意识到结果不是我所期望的。
然后,我修改了代码,尝试从Order表开始使用Subquery,但我注意到Order表没有item字段,在这种情况下在Django中使用Subquery似乎很困难。
因此,我编写了没有Subquery的代码,并设法访问了ItemPhoto.photo,但在某种程度上,它很复杂,很难在Template中使用。
如何使代码更好地从与字段不直接相关的表中引用字段?

queryset = Order.objects.prefetch_related( 
    Prefetch(
        'orderdetail_orderid', 
        queryset=OrderDetail.objects.select_related('order', 'item'),
        to_attr='oor',
    ),
).filter(user=user).order_by('-order')

# I could access to ItemPhoto.photo, but it's complicated.
[p.photo for q in queryset for i in q.orderdetail_orderid.all() for p in i.item.item_photo.all()]

models.py略)

class ItemCategory(models.Model):
    parent_id = models.IntegerField(default=0) 
    category_name = models.CharField(max_length=64, default="")
    category_type = models.IntegerField(default=0)

class Item(models.Model): # Product
    name = models.CharField(max_length=255, blank=False, default="")
    price = models.DecimalField(
        max_digits=12,
        decimal_places=2,
        default=0.00, 
        blank=False,
    ) 
    category = models.ForeignKey(ItemCategory, 
        on_delete=models.SET_NULL, null=True,
        related_name="item_category")

class ItemPhoto(models.Model):
    item = models.ForeignKey(Item, on_delete=models.CASCADE,
        related_name="item_photo",)
    photo = models.ImageField(blank=True, 
        upload_to=get_itemimage_path)

class Order(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, 
        on_delete=models.SET_NULL, 
        null=True, 
        related_name="order_user",
    )
    total_price = models.DecimalField(
        max_digits=12,
        decimal_places=2,
        default=0.00, 
    )
    created_at = models.DateTimeField(auto_now_add=True) 

class OrderDetail(models.Model):
    order = models.ForeignKey(Order, 
        on_delete=models.CASCADE,
        null=False,
        related_name="orderdetail_orderid",) 
    item = models.ForeignKey(Item,
        on_delete=models.SET_NULL,
        null=True, 
        related_name="orderdetail_item",)
# price
# quantity
    created_at = models.DateTimeField(auto_now_add=True)

Python:3.9 / Django:4.1 /数据库系统/ SQLite3

bq3bfh9z

bq3bfh9z1#

我碰巧想到了一种使用子查询的不同方法。

subqs = ItemPhoto.objects.filter(item=OuterRef('item')).filter(priority=1)

queryset = Order.objects.prefetch_related( 
    Prefetch(
        'orderdetail_orderid',
        queryset=OrderDetail.objects.select_related('order', 'item').annotate(
            item_photos=Subquery(subqs.values('photo')),
        ),
        to_attr='oor',
    ),
).filter(user=user)
prices = [o.price for q in queryset for o in q.oor]
photos = [o.item_photos for q in queryset for o in q.oor]

我可以更容易地ItemPhoto.photo使用Subquery访问www.example.com,尽管我不知道这是否是最好的方法。

相关问题