Reputation: 352
I am creating an API using the drf-nested-routers application for Django Rest Framework. 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.
My (abbreviated) models are:
#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()
I have created the following (abbreviated) Serializers for these models:
#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')
I also have my views.py and urls.py set up to do the routing properly.
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:
'User' object has no attribute 'tasks'.
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.
I'm at a loss here and would appreciate any assistance.
Upvotes: 0
Views: 451
Reputation: 352
I rubber-ducked it with my wife and figured out my problem.
I had 'related_name="sessions"' in my ForeignKey field for user in models.py.
I was missing that information in the ForeignKey field in the task model.
Hopefully someone else stumbles on this and can learn from my mistake.
Upvotes: 2