Search code examples
pythondjangomany-to-many

show friends in ManyToManyField


I am building a BlogApp and I am trying to access only friends in ManyToManyField. BUT it is not working for me.

What i am trying to do

I am trying to show only list of friends in ManyToManyField.

models.py

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE,default='',unique=True)
    full_name = models.CharField(max_length=100,default='')
    friends = models.ManyToManyField("Profile",blank=True)

class Video(models.Model):
    user = models.ForeignKey(User,on_delete=models.CASCADE,default='',null=True)
    add_users = models.ManyToManyField(Profile,related_name='taguser')

I want to access friends in Video model's ManyToManyField

What have i tried

  • I also did ManyToManyField('friends)` but it didn't worked for me.

I don't know what to do.

Any help would be Appreiated.

Thank You in Advance


Solution

  • Unless you define related_name in your Profile model OneToOneField User, Django will use lowercased model name to access related object. So, user.profile.

    Or also you can get the related friends objects to Video.user with _set:

    video = Video.objects.get(pk=pk)
    video.user.profile.friends
    # or 
    video.user.profile_set
    

    Note, you can remove unique (Django Docs) option from OneToOneField:

    This option is valid on all field types except ManyToManyField and OneToOneField.


    And to add friends to add_users:

    video.add_users.add(*video.user.profile.friends)
    

    Note that add(), create(), remove(), clear(), and set() all apply database changes immediately for all types of related fields. In other words, there is no need to call save() on either end of the relationship.