Django: assigning multiple values to a model field

Viewed 78

I'm trying to make a 'friendlist' function in django models and I'm having some problems. In my app, every user can make a name card. I want to let the users add each others as 'friends'(just like fb), so that I can make a friendlist for them.

This is what my models.py looks like so far.

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


# Create your models here.

class Card(models.Model):
    owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name="cards")
    # friend_list = models.????

I'd like to add a 'friend_list' attribute, which can store other cards' informations(I'm thinking of their pk values). Later, I'd like to iterate those values so that I can use it to make a friendlist in the template.

For example, "George's name card" should have information of its friends' cards' pk value.

Is there a way to save multiple values in one attribute?

1 Answers

You can use a ManyToManyField [Django-doc] to work with a collection of Users that relate to a single Card and multiple Cards that relate to a single User. You can thus rewrite this to:

from django.conf import settings
from django.db import models

class Card(models.Model):
    owner = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='owned_cards'
    )
    friends = models.ManyToManyField(
        settings.AUTH_USER_MODEL,
        related_name='befriended_cards'
    )
    # …

Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.

Related