0

I have a simple app that creates a Log entry for that day for each Child of a Parent when something happens to the Child.

So, for example, a Parent contains three Children.

Each time a Child is interacted with, I create an entry in the Log table to log the action. The Log is organized by day. So I could have 3 entries for three Children on Tuesday and 4 entries for the same three Children on Wednesday.

I want to write a query that checks to see if the Child exists in the Log for that day. So when the page loads, or is refreshed, I set a template variable that indicates that it does exist on the log.

I've been thinking that the following query will sort out what I need. But I'm having a hard time figuring out the missing parts.

Models:

class Child(models.Model):
    description = models.TextField()

class Log(models.Model):
    child = models.ForeignKey(Child, related_name="child_log")
    day = models.DateField(auto_now_add=True, editable=False)

class Parent(models.Model):
    parent_children = models.ManyToManyField(Child, blank=True, null=True)

Queryset:

today = date.today()
children = Child.objects.filter(parent=parent.id) <= parent.id comes from request kwargs
child_list = Child.objects.filter(id__contains=children.id)
does_exist = Log.objects.filter(child=child_list.id).filter(day=today)

But then I want to add that does_exist status to each Child in the template. That way I can show a different state if the Child has been logged or not.

Think of it like a todo list with todo items that can be done repeatedly in a day. If it's been done in a day, we need to show that it has been done. If it hasn't, then we can show that it hasn't.

I hope that is clear enough. Any suggestions are welcome.

2
  • Is there any relations in models? Show your models Feb 15, 2014 at 19:12
  • I added in the example models Feb 15, 2014 at 19:26

1 Answer 1

0

Hm... If I understand correctly, try this

{% for child in childs %}
    {% if child.child_log.today.exists %}
    #do your staff
...

And write manager to Log:

class LogManager(models.Manager)
    def today(self)
        return self.get_query_set().filter(day=datetime.datetime.today())

...
class Log(models.Model):
    child = models.ForeignKey(Child, related_name="child_log")
    day = models.DateField(auto_now_add=True, editable=False)

    objects = LogManager()
0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.