Django drf-nested-routers - model object has no attributed related field
<p>I am creating an API using the <a href="https://github.com/alanjds/drf-nested-routers" rel="nofollow">drf-nested-routers</a> application for <a href="http://www.django-rest-framework.org/" rel="nofollow">Django Rest Framework</a>. This application is a tracker where users have sessions and tasks. Each user can have three active tasks and can work on each of these tasks in a given session.</p>

<p>My (abbreviated) models are:</p>

<pre><code>#models.py
class User(models.Model):
    name = models.Charfield()

class Task(models.Model):
    start_date = models.Datefield()
    task_title = models.Charfield()
    user = models.ForeignKey(User, on_delete=models.CASCADE)

class Session(models.Model):
    session_date = models.Datefield()
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='sessions')
    task_one = models.ForeignKey(related_name="task_one")
    task_one_attempts = models.IntegerField()
    task_two = models.ForeignKey(related_name="task_two")
    task_two_attempts = models.IntegerField()
</code></pre>

<p>I have created the following (abbreviated) Serializers for these models:</p>

<pre><code>#serializers.py
class TaskSerializer(serializers.ModelSerializer):
     user = serializers.StringRelatedField(many=False)

    class Meta:
        model = Task
        fields = ('start_date', 'task_title', 'user')

 class SessionSerializer(serializers.ModelSerializer):
      user = Serializers.StringRelatedField(many=False)

      class Meta:
           model = Session
           fields = ('session_date', 'user', 'task_one', 'task_one_attempts', 'task_two', 'task_two_attempts')

class UserSerializer(models.ModelSerializer):
    sessions = SessionSerializer(many=True)
    tasks = TaskSerializer(many=True)
    sessions = SessionSerializer(many=True)

    class Meta:
         model = Users
         fields = ('name', 'sessions', 'tasks')
</code></pre>

<p>I also have my views.py and urls.py set up to do the routing properly.</p>

<p>I can navigate to the sessions and tasks API views just fine. However, whenever I try to navigate to the user view, it throws the following error:</p>

<pre><code>'User' object has no attribute 'tasks'.
</code></pre>

<p>What's really interesting, though, is that if I remove 'tasks' and just include sessions, it serializes everything just fine and gives me a nested view of the User's various sessions.</p>

<p>I'm at a loss here and would appreciate any assistance.</p>

<p>I rubber-ducked it with my wife and figured out my problem.</p>

<p>I had 'related_name="sessions"' in my ForeignKey field for user in models.py.</p>

<p>I was missing that information in the ForeignKey field in the task model.</p>

<p>Hopefully someone else stumbles on this and can learn from my mistake.</p>

python django django-rest-framework drf-nested-routers