简体   繁体   English

Django:给一个model字段赋多个值

[英]Django: assigning multiple values to a model field

I'm trying to make a 'friendlist' function in django models and I'm having some problems.我正在尝试在 django 模型中创建一个“好友列表”function,但我遇到了一些问题。 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.我想让用户将彼此添加为“朋友”(就像 fb 一样),这样我就可以为他们创建一个好友列表。

This is what my models.py looks like so far.这是我的 models.py 到目前为止的样子。

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).我想添加一个 'friend_list' 属性,它可以存储其他卡的信息(我在考虑它们的 pk 值)。 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.例如,“乔治的名片”应该有其朋友名片的pk值信息。

Is there a way to save multiple values in one attribute?有没有办法在一个属性中保存多个值?

You can use a ManyToManyField [Django-doc] to work with a collection of User s that relate to a single Card and multiple Card s that relate to a single User .您可以使用ManyToManyField [Django-doc]来处理与单个Card相关的User集合以及与单个User相关的多个Card集合。 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.注意:通常使用settings.AUTH_USER_MODEL [Django-doc]来引用用户 model 比直接使用User模型[Django-doc]更好。 For more information you can see the referencing the User model section of the documentation .有关详细信息,您可以参阅文档中引用User model的部分

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM