简体   繁体   English

Django ORM - 使用模型的 ManyToManyField 更新 ForeignKey 字段

[英]Django ORM - update ForeignKey field with model's ManyToManyField

I have a model:我有一个模型:

class User(AbstractUser):
   name = models.CharField(max_length=255)
   organizations = models.ManyToManyField(Organization)
   active_organization = models.ForeignKey(Organization)

Now I want to update active_organization with one of the organizations within the model, so I want to do something like this:现在我想用模型中的organizations之一更新active_organization ,所以我想做这样的事情:

User.objects.filter(active_organization=q).update(active_organization=F('organizations__pk')[0]) 

sadly F is not subscriptable, I've also tried,可悲的是 F 不是下标的,我也试过,

User.objects.filter(active_organization=q)\
                    .update(active_organization=Subquery(
                    Organization.objects.filter(pk=OuterRef('organizations').all()[0].pk)))

But in this case it tells me the OuterRef should be inside a SubQuery which it is, so I'm completely at a loss here how this should be approached.但在这种情况下,它告诉我OuterRef应该在OuterRef在的SubQuery内,所以我在这里完全不知该如何处理。

Try using the annotate create a field to then use in the update statement.尝试使用 annotate 创建一个字段,然后在更新语句中使用。

User.objects.filter(active_organization=q).annotate(
    next_active_org_id=Subquery(
        Organization.objects.filter(
            user_set__id=OuterRef('pk')
        ).values('id')[:1]
    )
).update(active_organization=F('next_active_org_id'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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