【问题标题】:How to store a List in a Django model如何在 Django 模型中存储列表
【发布时间】:2014-10-15 14:57:14
【问题描述】:

如何在我的 Django model.py 中为每个 User 存储 Livre 列表?

看起来像:

class Livre(models.Model):
    auteur = models.ForeignKey(Auteur)
    titre = models.CharField(max_length=50)
    genre = models.ForeignKey(Genre)
    publish_date = models.DateField()

我希望我的User 可以随心所欲地使用Livre(0 是可能的):

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

class Lecteur(User):
    bibliotheque = models.??????(Livre)

...无需接触Livre 模型。

简而言之,我想要一个从 UserLivre 的 OneToMany 关系。

【问题讨论】:

    标签: python django model one-to-many


    【解决方案1】:

    只需在用户模型中添加ManyToManyField

    您实际上需要ManyToMany 关系而不是OneToMany 关系,因为您希望多个用户能够将同一个Livre 链接到他们,对吧?

    如果没有,您可以通过覆盖 save() 方法来限制它(只需添加检查),或者您可以争辩说这实际上应该是 Livre 的责任,并在那里添加 ForeignKey

    您可以在此处找到有关ManyToManyField 的更多信息:https://docs.djangoproject.com/en/dev/topics/db/examples/many_to_many/

    【讨论】:

    • 您完全正确,ManyToMany 更适合我的问题。感谢您的光 ch3ka。
    猜你喜欢
    • 2022-08-16
    • 2016-07-15
    • 1970-01-01
    • 2013-04-09
    • 2019-08-09
    • 1970-01-01
    • 1970-01-01
    • 2016-02-11
    • 2019-10-22
    相关资源
    最近更新 更多