本文介绍了与Django左外部连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个人,该人具有 User 的外键:

I have a person, which has a foreign key to User:

p = Personne.objects.get(user=self.request.user)

此人通过模型 PersonneRelation 有朋友,其中有一个 src 人和一个 dst 人,因此我正在像这样检索该人的所有朋友:

This person has "friends" through the model PersonneRelation where there's a src person and a dst person, so I'm retrieving all the person's friends like this:

friends = [a.dst.pk for a in PersonneRelation.objects.filter(src=p)]

我有一个模型旅行嵌入旅行说明。我还有一个模型活动,它是朋友当前用户已完成的活动(活动)。因此,这就是我检索与当前用户有关的所有活动的方式:

I have a model Travel which embeds a description of a travel. I have also a model "activity" which is an activity the friend's current user have done (Activite). So here's the way I'm retrieving all the activities related to the current user:

context['activites'] = Activite.objects.filter(
    Q(travel__personne__pk__in=friends) | Q(relation__src__pk__in=friends),
)

一切正常。我还有一个模型 PersonneLiked ,如果您喜欢 Activite ,可以精确定位。因此,该模型具有 Activite 的外键。

Everything works fine. I have also a model PersonneLiked where you precise if you liked an Activite. Thus this model has a foreign key to Activite.

class PersonneLiked(models.Model):
    src = models.ForeignKey('Personne', related_name='liked_src')
    dst = models.ForeignKey('Personne', related_name='liked_dst')
    activite = models.ForeignKey('Activite', related_name='liked_activite')
    # liked = thumb added *OR* removed :
    liked = models.BooleanField(default=True)

检索所有<$ PersonneLiked 的代码是什么c $ c> context ['activites'] ?就像在SQL中创建外部联接,但我不知道如何使用Django。

What is the code I should do to retrieve all the PersonneLiked of context['activites']? It's like making an OUTER JOIN in SQL, but I dont know how I could do this with Django.

推荐答案

由于 context ['activities'] 是适当的 Activite 对象的查询集那么您可以这样做:

Since context['activities'] is a queryset of the appropriate Activite objects then you can do:

PersonneLiked.objects.filter(activite__in=context['activities'])

(请注意,如果这是M2M关系而不是ForeignKey,则此方法将在最终查询集中创建重复的条目。)

(Note that if this were a M2M relationship rather than a ForeignKey, this method would create duplicate entries in your final queryset.)

这篇关于与Django左外部连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 06:13