Django ManyToManyField外键设计

时间:2015-01-18 02:54:08

标签: django

作为地址簿应用程序的一部分,我在models.py

中有以下内容
from django.db import models

class Contact(models.Model):
    contact_id= models.AutoField(auto_created=True, primary_key=True, default=1, verbose_name='ID')
    name = models.CharField(max_length=100, unique=True)
    contact_no = models.ManyToManyField(ContactNumberTypeField, 
                 through='ContactContactNumber', through_fields=('contact_name','contact_type'))

    def __str__(self):
        return self.name

class ContactNumberTypeField(models.Model):
    contact_number_type=models.AutoField(auto_created=True, primary_key=True, default=1, verbose_name='ID')
    name = models.CharField(max_length=20)
    contact_no = models.ManyToManyField(Contact, 
                 through='ContactContactNumber', through_fields=('contact_name','contact_type'))
    def __str__(self):
        return self.name             

class ContactContactNumber(models.Model):
    contact_name=models.ForeignKey(Contact)
    contact_type=models.ForeignKey(ContactNumberTypeField)
    contact_number = models.CharField(max_length=50)

    def __str__(self):
        return contact_number

我的问题是,为什么当我运行 makemigrations 时,会抛出 ContactNumberTypeField未定义错误?

更新

正确的代码如下

from django.db import models

class Contact(models.Model):
    contact_id= models.ManyToManyField('ContactNumberTypeField', 
                 through='ContactContactNumber', through_fields=('contact_name','contact_type'))
    name = models.CharField(max_length=100, unique=True)


    def __str__(self):
        return self.name

class ContactNumberTypeField(models.Model):
    contact_number_type=models.ManyToManyField('Contact', 
                 through='ContactContactNumber', through_fields=('contact_type','contact_name'))
    name = models.CharField(max_length=20)
    contact_no = models.IntegerField(max_length=20)
    def __str__(self):
        return self.name             

class ContactContactNumber(models.Model):
    contact_name=models.ForeignKey(Contact)
    contact_type=models.ForeignKey(ContactNumberTypeField)
    contact_number = models.CharField(max_length=50)

    def __str__(self):
        return contact_number

1 个答案:

答案 0 :(得分:1)

在定义ContactNumberTypeField类时未定义

Contact。将contact_no字段更改为:

class Contact(models.Model):
    ...
    contact_no = models.ManyToManyField('ContactNumberTypeField', 
                 through='ContactContactNumber',
                 through_fields=('contact_name','contact_type'))

请注意'ContactNumberTypeField'周围的引号。

此处的另一个错误是through_fields字段的ContactNumberTypeField.contact_no属性中字段名称的顺序错误。它应该是:

class ContactNumberTypeField(models.Model):
    ...
    contact_no = models.ManyToManyField(Contact, 
                 through='ContactContactNumber',
                 through_fields=('contact_type','contact_name'))

阅读documentation关于 field1 field2