【问题标题】:How to do a reverse lookup through a profile in django如何通过 django 中的配置文件进行反向查找
【发布时间】:2011-12-31 21:40:38
【问题描述】:

所以我有一个类,Y,它是一个扩展用户的配置文件。

我有另一个类 X,它与类 Y 是一对一的关系:

class X(models.Model):
    y = models.ForeignKey('class Y')

鉴于我可以访问用户对象,我如何访问与之关联的 X?

【问题讨论】:

    标签: django reverse-lookup


    【解决方案1】:

    您需要关注something along these lines

    #your user object
    user = User.objects.get(name="John Doe")
    
    #returns all x objects related to the user
    #i say all objects because using a foreign key is a one to many relationship, not necessarily a one to one relationship
    X_objects = user.x_set.all()
    
    #if you need to reduce it down to one object (assuming you do assign it to more than one)
    X_object = user.x_set.filter(some_field__someCondition = 'something');
    

    【讨论】:

    • Y 类的存在会使这一切复杂化吗?
    • 试一试,让我知道会发生什么。如果它不起作用,请告诉我们它的作用,我们将从那里开始工作
    • 我实际上是通过使用三个不同的查找设置三个变量来完成这项工作的。不优雅,但它成功了。
    猜你喜欢
    • 2011-05-09
    • 2015-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-21
    • 2018-10-15
    • 2011-03-22
    • 1970-01-01
    相关资源
    最近更新 更多