简体   繁体   English

Django:通过另一个模型访问模型的字段

[英]Django: Accessing a model's field through a another model

So I have 2 models: 所以我有2个模型:

class Product(models.Model):
    BANANA = 'BAN'
    PRODUCT_CHOICES = (
        (BANANA, 'Banana'),
    ) 

    name = models.CharField(choices=PRODUCT_CHOICES, max_length=255, default=BANANA)
    shelf_life = models.IntegerField(null=True, blank=True)

class PurchasedOrder(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    purchased_date = models.DateTimeField(auto_now_add=True)
    expired = models.BooleanField(default=False)

GOAL: To get all my purchased orders that are not expired and its purchased date is less than the time now and the product's shelf life. 目标:要获取我所有尚未过期的购买订单,并且购买日期少于现在的时间和产品的保质期。

I tried the following sudo code ish, and I would like to know how to access this PurchasedOrder's product shelf life, as Purchase Order has a Foreign key to Product. 我尝试了以下sudo代码ish,并且我想知道如何访问PurchasedOrder的产品保质期,因为Purchase Order具有产品的外键。 I could create some of for loop, but there must be a way to access the product's shelf life field though the PurchaseOrder. 我可以创建一些for循环,但是必须有一种方法可以通过PurchaseOrder访问产品的保质期字段。

PurchasedOrder.objects.filter(
    expired=False,
    purchased_date__lt=F(datetime.now() - product__shelf_life),
)

I will appreciate your help <3 感谢您的帮助<3

This answer should solve it for you if you're using PostgreSQL. 如果您使用的是PostgreSQL,那么此答案应该可以为您解决。

from datetime import timedelta
from django.utils import timezone

now = timezone.now()
PurchasedOrder.objects.filter(
    expired=False,
    purchased_date__lt=now - timedelta(days=1)*F("product__shelf_life"),
)

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

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