1

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

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

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

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

4

1 回答 1

0

您需要遵循这些原则

#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');
于 2011-11-18T15:31:13.707 回答