Anthony
Anthony

Reputation: 979

Django: Accessing a model's field through a another model

So I have 2 models:

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. I could create some of for loop, but there must be a way to access the product's shelf life field though the PurchaseOrder.

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

I will appreciate your help <3

Upvotes: 0

Views: 66

Answers (1)

schillingt
schillingt

Reputation: 13731

This answer should solve it for you if you're using 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"),
)

Upvotes: 1

Related Questions