Django:模型设计,ManyToMany 属性字段?
Django: Model Design, ManyToMany attribute fields?
以这种方式处理数据库还很陌生。我在下面有一些示例代码。我有乐器对象,它将是乐器、吉他、钢琴等类型的数据库列表。然后用户对象将在其上有一个 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)
似乎是 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')
以这种方式处理数据库还很陌生。我在下面有一些示例代码。我有乐器对象,它将是乐器、吉他、钢琴等类型的数据库列表。然后用户对象将在其上有一个 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)
似乎是 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')