【问题标题】:Django: Model Design, ManyToMany attribute fields?Django:模型设计,ManyToMany 属性字段?
【发布时间】:2016-10-12 12:11:58
【问题描述】:

以这种方式处理数据库非常新。我在下面有一些示例代码。我有乐器对象,它将是乐器、吉他、钢琴等类型的数据库列表。然后用户对象将有一个 ManyToMany,因此每个用户可以在他们的个人资料中列出尽可能多的他们演奏。

我坚持的是,我希望有一个领域来体验这些乐器中的每一种。只是不确定如何在没有静态字段的情况下完成此操作,因为会有多少仪器(因为它是可修改的,所以可能会改变)。感谢您指出正确的方向。

class Instrument(models.Model):

    # Name of the instrument
    name = models.CharField(_('Name of Instrument'), blank=True, max_length=255)


    def __str__(self):
        return self.name

    class Meta:
        ordering = ('name',)

@python_2_unicode_compatible
class User(AbstractUser):

    # First Name and Last Name do not cover name patterns
    # around the globe.
    name = models.CharField(_('Name of User'), blank=True, max_length=255)
    zipcode = models.IntegerField(_('Zip Code of the User'), blank=True, null=True)
    instruments = models.ManyToManyField(Instrument)

【问题讨论】:

    标签: sql django database models


    【解决方案1】:

    似乎是 through model with extra fields 的教科书用例。

    class InstrumentExperience(models.Model):
        user = models.ForeignKey('User')
        instrument = models.ForeignKey('Instrument')
        experience = models.CharField(max_length=100)
    
    class User(AbstractUser):
        ...
        instruments = models.ManyToManyField('Instrument', through='InstrumentExperience')
    

    【讨论】:

    • 谢谢!正是我需要的。
    猜你喜欢
    • 2016-04-29
    • 1970-01-01
    • 2011-04-26
    • 1970-01-01
    • 2019-09-04
    • 2022-01-24
    • 1970-01-01
    • 2019-01-07
    • 2016-02-10
    相关资源
    最近更新 更多