Django - trouble with separating objects by user and date
<p>So I have these models: </p>

<pre><code>excercises_choices = (('Bench Press', 'Bench press'),('Overhead Press', 'Overhead Press'), ('Squat', 'Squat'),
                ('Deadlift', 'Deadlift'))

unit_choices = (('kg','kg'), ('lbs', 'lbs'))


class Lifts(models.Model):

 user = models.ForeignKey('auth.User', null=True)
 excercises = models.CharField(max_length=200, choices=excercises_choices)
 sets = models.IntegerField(null=True, blank=True)
 reps = models.IntegerField(null=True, blank=True)
 weight = models.FloatField()
 unit = models.CharField(max_length=3, choices=unit_choices)
 created_date = models.ForeignKey('Dates')
 amrap_set = models.BooleanField(default=False)
 amrap_rep = models.IntegerField(null=True, blank=True)

def __str__(self):
    return self.excercises


class Dates(models.Model):
 created_date = models.DateField(unique=True)

def __str__(self):
    return str(self.created_date)
</code></pre>

<p>Let's say I have few lifts at different dates for admin and few lifts at different for xx user. 
I want multiple lifts matching one date that's why I've made foreign key. (eg. 3 lifts to 2016-10-10 and 2 lifts to 2016-10-11).</p>

<p>Here is a view for showing it:</p>

<pre><code> @login_required
 def entries(request):
  date = Dates.objects.all().order_by('-created_date')
  lifts_by_user = Lifts.objects.filter(user=request.user)
  return render(request, 'lift/entries.html', {'date': date,
                                             'lifts_by_user': lifts_by_user})
</code></pre>

<p>And template: </p>

<pre><code>{% extends 'lift/base.html' %}

{% block content %}
{{ user }}


{% if user.is_authenticated %}

{% for date in date %}
    &lt;p&gt;&lt;strong&gt;&lt;a href="{% url 'lift_date' pk=date.pk %}"&gt;{{ date }}&lt;/a&gt;&lt;/strong&gt;
    {% for i in date.lifts_set.all %}
        {{ i }}

    {% endfor %}

&lt;a href="{% url 'new_lifts' %}"&gt;add new lift&lt;/a&gt;&lt;/p&gt;
{% endfor %}
{% endif %}
&lt;p&gt;
&lt;a href="{% url 'entries_delete' %}"&gt;Delete lifts or dates &lt;/a&gt;
&lt;/p&gt;
{% endblock %}
</code></pre>

<p>The problem is that I dont know how to separate it by dates AND by user.
<a href="https://i.stack.imgur.com/0gljf.png" rel="nofollow">This is how it looks like</a> How do i keep this pattern date - lifts_to_that_date but for separate users? I dont want to see admin's entries while I am on test user</p>

<p>Have a look at the <a href="https://docs.djangoproject.com/en/dev/ref/templates/builtins/#regroup" rel="nofollow">regroup</a> template tag, it does exactly what you need.</p>

<p>You can do something like this in your view:</p>

<pre><code>@login_required
def entries(request):
    lifts_by_user = (Lifts.objects.filter(user=request.user)
        .order_by('-created_date__created_date'))
    return render(
        request,
        'lift/entries.html',
        {'lifts_by_user': lifts_by_user}
    )
</code></pre>

<p>And replace the <code>for date in dates</code> loop in your template with something like:</p>

<pre><code>{% regroup lifts_by_user by created_date.created_date as lifts %}
&lt;ul&gt;
    {% for day in lifts %}
        &lt;li&gt;Date: {{ day.grouper }}
            &lt;ul&gt;
                {% for lift in day.list %}
                    &lt;li&gt;{{ lift }}&lt;/li&gt;
                {% endfor %}
            &lt;/ul&gt;
        &lt;/li&gt;
    {% endfor %}
&lt;/ul&gt;
</code></pre>

<p>I've used a <code>ul</code> here so that it's easier to compare to the example in the docs, but obviously you can change the markup to whatever you need. It's important to know that regroup doesn't order its input, so you need to order by created_date in your view.</p>

<p>If you're using Django's dev version you can use this instead:</p>

<pre><code>{% regroup lifts_by_user by created_date.created_date as lift_list %}
&lt;ul&gt;
    {% for day, lifts in lift_list %}
        &lt;li&gt;Date: {{ day }}
            &lt;ul&gt;
                {% for lift in lifts %}
                    &lt;li&gt;{{ lift }}&lt;/li&gt;
                {% endfor %}
            &lt;/ul&gt;
        &lt;/li&gt;
    {% endfor %}
&lt;/ul&gt;
</code></pre>

<p>Which I think is a little clearer.</p>

<p>As an aside, none of this relies on having dates stored as a foreign key, but that's up to you.</p>

<h2>Questions from comments:</h2>

<ol>
<li><p><code>order_by('-created_date__created_date')</code> is joining Lifts to Dates through the Lifts.created_date foreign key and ordering by the Dates.created_date field. Have a look at <a href="https://docs.djangoproject.com/en/dev/topics/db/queries/#lookups-that-span-relationships" rel="nofollow">https://docs.djangoproject.com/en/dev/topics/db/queries/#lookups-that-span-relationships</a> for details.</p></li>
<li><p><code>for day, lifts in lift_list</code> is using tuple unpacking.
As a quick example:</p>

<pre><code>t = (1, 2, 3)
# first, second, third will have values 1, 2, 3 respectively
first, second, third = t
</code></pre>

<p><code>{% regroup lifts_by_user by created_date.created_date as lifts_list %}</code> produces a list of <a href="https://docs.python.org/3/library/collections.html#collections.namedtuple" rel="nofollow">namedtuples</a> (again, only in the dev version, if you're using 1.10 or earlier it's a list of dicts so you can't use this trick) so as you're iterating through lift_list you can unpack the date and list of lifts into separate variables.</p></li>
<li><p>If you have a Lift instance called lift, you can get the pk for its date by using <code>lift.created_date_id</code>. Accessing it where you have the date URL in your example template is a little trickier because you have to get a lift out of the regrouped date's list. Something like this:</p>

<pre><code>{% regroup lifts_by_user by created_date.created_date as lifts %}
&lt;ul&gt;
    {% for day in lifts %}
        &lt;li&gt;Date: {{ day.grouper }}
            {# day.list.0 gets the first lift for this day #}
            Date PK: {{ day.list.0.created_date_id }}
            &lt;ul&gt;
                {% for lift in day.list %}
                    &lt;li&gt;{{ lift }}&lt;/li&gt;
                {% endfor %}
            &lt;/ul&gt;
        &lt;/li&gt;
    {% endfor %}
&lt;/ul&gt;
</code></pre></li>
</ol>

python django web-applications django-models django-templates