如何通过Django中的RelatedManager访问“调用”对象?

时间:2021-05-25 05:04:05

Say I have a model with a foreign key to a Django Auth user:

假设我有一个对Django Auth用户具有外键的模型:

class Something(models.Model):

    user = models.ForeignKey(User, related_name='something')

I can then access this model through a RelatedManager:

然后我可以通过一个RelatedManager访问这个模型:

u = User.objects.create_user('richardhenry', 'richard@example.com', 'password')
u.something.all()

My question is, if I create a SomethingManager and define some methods on it:

我的问题是,如果我创建一个SomethingManager并定义一些方法:

class SomethingManager(models.Manager):

    def do_something(self):
        pass

Is it possible to get the original User object (as in, the variable u) within the do_something() method? (Through the related manager; passing it in via the method args isn't what I'm after.)

是否可能在do_something()方法中获取原始的用户对象(如变量u) ?(通过相关经理;通过方法args传入它并不是我想要的)

1 个解决方案

#1


2  

Managers are only directly connected to the model they manage. So in this case, your Manager would be connected to Something, but not directly to User.

管理人员只是直接连接到他们管理的模型。在这种情况下,你的管理器会连接到某个东西,但不是直接连接到用户。

Also, Managers begin with querysets, not objects, so you'll have to work from there.

而且,管理器从querysets而不是对象开始,因此您必须从那里开始工作。

Keep in mind that to use your custom methods with a RelatedManager you need to set use_for_related_fields = True in your Manager.

请记住,要在RelatedManager中使用自定义方法,您需要在管理器中设置use_for_related_fields = True。

So to get to the user, you'd have to be a bit roundabout and get the object, then the user:

所以要找到用户,你必须有点圆滑地找到对象,然后用户:

def do_something(
    ids = self.get_query_set().values_list('user__id', flat=True)
    return User.objects.filter(id__in=ids).distinct()

The above should return just one user, you could add a .get() at the end to get the object instead of a queryset, but I like returning querysets since you can keep chaining them.

上面应该只返回一个用户,您可以在末尾添加.get()来获取对象,而不是查询集,但是我喜欢返回查询集,因为您可以继续链接它们。

#1


2  

Managers are only directly connected to the model they manage. So in this case, your Manager would be connected to Something, but not directly to User.

管理人员只是直接连接到他们管理的模型。在这种情况下,你的管理器会连接到某个东西,但不是直接连接到用户。

Also, Managers begin with querysets, not objects, so you'll have to work from there.

而且,管理器从querysets而不是对象开始,因此您必须从那里开始工作。

Keep in mind that to use your custom methods with a RelatedManager you need to set use_for_related_fields = True in your Manager.

请记住,要在RelatedManager中使用自定义方法,您需要在管理器中设置use_for_related_fields = True。

So to get to the user, you'd have to be a bit roundabout and get the object, then the user:

所以要找到用户,你必须有点圆滑地找到对象,然后用户:

def do_something(
    ids = self.get_query_set().values_list('user__id', flat=True)
    return User.objects.filter(id__in=ids).distinct()

The above should return just one user, you could add a .get() at the end to get the object instead of a queryset, but I like returning querysets since you can keep chaining them.

上面应该只返回一个用户,您可以在末尾添加.get()来获取对象,而不是查询集,但是我喜欢返回查询集,因为您可以继续链接它们。