Home > Mobile >  Better way to fetch related object, in Self Refrencing ManyToMany Relationship?
Better way to fetch related object, in Self Refrencing ManyToMany Relationship?

Time:09-28

I am working on a small application containing models CustomUser and PollQuestion. CustomUser having ManyToMany relation between itself and a CustomUser can have multiple PollsQuestion as well so there is Foreign Key relation between them. An authenticated user is only able to see polls raised by users he is following, to full-fill this requirement i have written following view**:-** Actually this is not view this is an utility method returning the polls to original view.

def all_polls_utils(request):
    following = request.user.get_all_followings().values_list("id")
    user_id = [id[0] for id in following]
    all_polls = PollQuestion.objects.none()
    for u_id in user_id:
        user = CustomUser.objects.get(id=u_id)
        polls = user.poll_questions.all()
        all_polls = all_polls | polls
    return all_polls

Main Question:- Is there in better way to do the same? Any suggestion will be highly appretiated

I am posting the models bellow:-

from django.db import models
from django.contrib.auth.models import AbstractUser


# Create your models here.
class CustomUser(AbstractUser):
    email = models.EmailField(max_length=250, null=False)
    name = models.CharField(max_length=50, null=False)
    username = models.CharField(max_length=50, null=False, unique=True)
    password = models.CharField(max_length=15, null=False)
    user = models.ManyToManyField('self', through='Relationship', symmetrical=False, related_name='related_to')

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['name', 'email']

    def get_all_polls(self):
        pass

    def create_relationship(self, person):
        status, obj = Relationship.objects.get_or_create(
            to_person=person,
            from_person=self,
        )
        return status

    def remove_relationship(self, person):
        Relationship.objects.filter(
            from_person=self,
            to_person=person
        ).delete()
        return 'dummy_value'

    def get_all_followings(self):
        return self.user.all()


class Relationship(models.Model):
    from_person = models.ForeignKey(CustomUser, related_name='from_people', on_delete=models.CASCADE)
    to_person = models.ForeignKey(CustomUser, related_name='to_person', on_delete=models.CASCADE)

And PollQuestion:-

class PollQuestion(models.Model):
    user = models.ForeignKey(CustomUser, null=True, on_delete=models.CASCADE, related_name="poll_questions")
   # Other fields

Note:- You can also suggest me a better title for this post?

Thanks in advance, Hope to here from you soon.

CodePudding user response:

Simply

def all_polls_utils(request):
    all_polls_by_followed = PollQuestion.objects.filter(
        user__in=request.user.get_all_followings()
    )

As an aside, you should probably rename the user many-to-many in CustomUser to e.g. followed_users (with a related name followers).

  • Related