Django ManyToMany字段不是在模型中创建的 [英] Django ManyToMany field is not created in model

查看:78
本文介绍了Django ManyToMany字段不是在模型中创建的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  class Teacher(个人资料):
class Meta:
db_table ='teacher'

user = models.OneToOneField(User,
unique = True,
verbose_name = _('user'),
related_name = 'teacher')

home_address = models.CharField(_('home_address'),max_length = 255,blank = True)
home_phone = models.CharField(_('home_phone' max_length = 30,blank = True)
cell_phone = models.CharField(_('cell_phone'),max_length = 30,blank = True)
experience = models.IntegerField(default = 0)
summary = models.TextField(_('summary'),max_length = 500,blank = True)
subjects = models.ManyToManyField(Subjects,through ='SubjectsIntermediate')

当我执行 manage.py syncdb 时,它会创建老师表,除了字段主题之外的所有字段。为什么没有创建主题字段?

解决方案

因为ManyToMany不是一个字段,至少不是一个作为数据库列存在的字段。这是与链接表的关系。您会发现,创建了一个名为 myapp_teacher_subjects 的表,其中包含老师和主题的外键。


Here is my Model for Teacher class.

class Teacher(Profile):
    class Meta:
        db_table = 'teacher'

    user = models.OneToOneField(User,
                                unique=True,
                                verbose_name=_('user'),
                                related_name='teacher')

    home_address =  models.CharField(_('home_address'), max_length=255, blank=True)
    home_phone =  models.CharField(_('home_phone'), max_length=30, blank=True)
    cell_phone =  models.CharField(_('cell_phone'), max_length=30, blank=True)
    experience =  models.IntegerField(default = 0)
    summary =  models.TextField(_('summary'), max_length=500, blank=True)
    subjects = models.ManyToManyField(Subjects, through='SubjectsIntermediate')

When i execute the manage.py syncdb it does creates the teacher table with all fields except for field subjects. Why the subjects field is not created??

解决方案

Because a ManyToMany isn't a field, at least not one that exists as a database column. It's a relationship with a linking table. You'll find that a table named myapp_teacher_subjects has been created, with foreign keys to both teacher and subjects.

这篇关于Django ManyToMany字段不是在模型中创建的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆