Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Django:如何在应用程序中创建多个字段_Python_Django_Django Models_Many To Many_Django Orm - Fatal编程技术网

Python Django:如何在应用程序中创建多个字段

Python Django:如何在应用程序中创建多个字段,python,django,django-models,many-to-many,django-orm,Python,Django,Django Models,Many To Many,Django Orm,我试图扩展auth.models组以获得一些额外的字段。以下是我在myapp.models.py中所做的工作: class ProfileGroupBase(type): def __new__(cls, name, bases, attrs): module = attrs.pop('__module__') parents = [b for b in bases if isinstance(b, ProfileGroupBase)] i

我试图扩展auth.models组以获得一些额外的字段。以下是我在myapp.models.py中所做的工作:

class ProfileGroupBase(type):
    def __new__(cls, name, bases, attrs):
        module = attrs.pop('__module__')
        parents = [b for b in bases if isinstance(b, ProfileGroupBase)]
        if parents:
            fields = []
            for obj_name, obj in attrs.items():
                if isinstance(obj, models.Field): fields.append(obj_name)
                Group.add_to_class(obj_name, obj)
        return super(ProfileGroupBase, cls).__new__(cls, name, bases, attrs)

class ProfileGroup(object):
    __metaclass__ = ProfileGroupBase

class MyGroup(ProfileGroup):
    mobile = models.CharField(max_length = 15)
    email = models.CharField(max_length = 15)
使用这些代码,移动和电子邮件字段将添加到管理页面上的组中。现在我想添加另一个manytomany字段,所以我在MyGroup类(ProfileGroup)下添加了这个字段:

然后,我在同一models.py文件下创建了一个新的模型注释:

class Annotation(models.Model):
    index = models.IntegerField()
    name = models.CharField(max_length = 100)

但是,出现了一个错误:未定义名称“Annotation”。我想知道,即使类MyGroup和类Annotation是在同一个models.py下定义的,它们实际上是分开的。我很困惑,有人知道这里发生了什么吗?谢谢。

让我猜猜,您是在具有多对多关系的上一个模型之后定义了
注释
模型的

class Annotation(models.Model):
    index = models.IntegerField()
    name = models.CharField(max_length = 100)

只需剪切
注释
模型的代码,并将其粘贴到另一个模型之前。

定义ForeignKey或ManyToManyField时,应使用包含应用程序名称和模型名称的字符串而不是实际类来定义另一个类。这样做吧

annotations = models.ManyToManyField('myapp.Annotation', verbose_name=_('annotation'), blank=True) annotations=models.ManyToManyField('myapp.Annotation', 详细名称=(注释),空白=真)
这有助于引用尚未定义的模型,也有助于循环引用。所以我建议一直这样做。还请查看foreignkey文档:

Oops,我忘了这一点……谢谢。但它报告了另一个错误:“MyGroup”类中的本地字段“annotations”与基类“Group”中类似名称的字段冲突。
MyGroup(ProfileGroup):
继承自
ProfileGroup
,请发布您的
ProfileGroup
类。啊,等等,
元类\UUUUUUUU=ProfileGroupBase
,请粘贴
ProfileGroupBase
基类。 annotations = models.ManyToManyField('myapp.Annotation', verbose_name=_('annotation'), blank=True)