Select a single field from a foreign key

后端 未结 1 1114
自闭症患者
自闭症患者 2020-12-11 21:55

So I have a a very simple (simplified) model

class MyObject(models.Model):
    owning_user = models.ForeignKey(User, null=True)

Now in one

相关标签:
1条回答
  • 2020-12-11 23:00

    If you use my_object.owning_user_id instead of my_object.owning_user, then Django will use the id instead of looking up the user.

    In this case, you only need the id, but if you needed other user attributes, you could use select_related. In the view, you would do:

    foo.my_object_set.select_related('user')
    

    In the template, you don't have as much control, since you can't pass arguments.

    {{ foo.my_object_set.select_related }}
    
    0 讨论(0)
提交回复
热议问题