简体   繁体   中英

Django: Related Objects for Authenticated User

In Django we can create related models:

class User(models.Model):
    pass

class TaskSet(models.Model):
    user = models.ForeignKey(User, related_name='tasksets')
    title = models.Charfield()

class Task(models.Model):
    user = models.ForeignKey(User, related_name='tasks')
    taskset = models.ForeignKey(TaskSet, related_name='tasks')

Makes sense, I can call request.user.tasksets – but what's the correct way to get the tasks in the taskset? request.user.tasksets.first().tasks will return all of the tasks for the entire task set– but how can I get the tasks for that user only?

You can call .filter() on that. So the whole query would be request.user.tasksets.first().tasks.filter(user=request.user) . However, this is only useful if you want to get a task from the first task set of the user only and this structure would only be productive if the tasks defined inside each task set can belong to other users other than the task set owner.

If you just want to get a task belonging to that user regardless of whether it is in the first task set or not, you can do request.user.tasks.first() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM