1

models.py

class Box(models.Model):
    length  = models.IntegerField(null=False)
    width   = models.IntegerField(null=False)
    height  = models.IntegerField(null=False)

class BoxColorHistory(models.Model):
    box            = models.ForeignKey(Box, related_name='color_history')
    start_datetime = models.DateTimeField(null=False)
    end_datetime   = models.DateTimeField(null=True)
    color          = models.CharField(max_length=20)

I would like to write a query that returns all Boxes that have current color='green'.

The problem is that the color is constantly changing. Each time the color changes, this is recorded in the BoxColorHistory table.

The current color of the box is the row in the BoxColorHistory table with the most recent start time and an end time of null.

2 Answers 2

1
current_green_histories = BoxColorHistory.objects.filter(
    end_datetime__isnull=True,
    color='green'
)
Box.objects.filter(color_history__id__in=current_green_histories.values('id'))
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I'm a newbie and confused, though -- where does color_history come from? The Box only has length, width, height fields.
0

Try:

Box.objects.filter(color_history__color='green')

1 Comment

Every box has been green at some point. I just want the ones that are green now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.