flice com
flice com

Reputation: 125

Django merge 2 querysets overide annotation

I have 2 models. Followers Influencers

class Influencer(models.Model):
    username = models.CharField(
        _("username"), max_length=250, unique=True, null=False, blank=False, db_index=True)
    followers = models.ManyToManyField(
        "instagram_data.Follower", verbose_name=_("Followers"))

I want to create a QS of followers from 2 influencers:

influencer_choosen_by_user = [influ1name, influ2name]

qs = Follower.objects.none()
qs_influencers = Influencer.objects.filter(username__in=influencer_choosen_by_user)
for influencer_obj in qs_influencers.iterator():
    followers_of_influ_qs = influencer_obj.followers.all()  # get all followers of this influencer
    followers_of_influ_qs = followers_of_influ_qs.annotate(
        influencer_source=Value(f'followers/{influencer_obj.username}', CharField()))
    qs = qs | followers_of_influ_qs

EXPECTED RESULTS:

qs = <[followers1,influ1name] , [followers2, influ2name], [followers3, influ2name]>

NOTE:

A follower can follow many influencers

ISSUE:

All qs are of influencer_source == influ1name none of influ2name !!!

Why ?

Upvotes: 1

Views: 77

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477608

You can annotate the followers with an extra attribute that determines the username of that Influencer with:

from django.db.models import F

Follower.objects.filter(
    influencer__username__in=influencer_choosen_by_user
).annotate(
    influencer=F('influencer__username')
)

In that case the Follower objects will have an extra attribute .influencer which contains the username of the influencer. If a follower follows multiple influencers, the follower will occur twice or more in the queryset, each time with .influencer another username of the influencer_choosen_by_user.

Upvotes: 1

Related Questions