Django:ManyToMany关联名称未定义

时间:2018-04-23 19:21:24

标签: python django

这是我的models.py

from django.db import models
from django.urls import reverse
from django.contrib.auth.models import User
from userprofiles.models import UserProfile
# Create your models here.

import os

class Category (models.Model):
    name = models.CharField(max_length=100)
    def __str__(self):
        return self.name

class Image(models.Model):
    owner = models.ForeignKey(UserProfile, on_delete=models.CASCADE)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    in_gallery = models.ManyToManyField(Gallery)
    title = models.CharField(max_length=100)
    def __str__(self):
        return self.title

class Gallery(models.Model):
    name = models.CharField(max_length=100)
    have_images = models.ManyToManyField(Image)

    def __str__(self):
        return self.name

class ImageInGallery (models.Model):
    image = models.ForeignKey(Image)
    gallery = models.ForeignKey(Gallery)


line 22, in Image     in_gallery = models.ManyToManyField(Gallery)
NameError: name 'Gallery' is not defined

我希望图像和图库以及类ImageInGallery有很多关系来存储Image~Gallery关系集。

另外,我希望图库中的图片可以从图库中访问,反之亦然,因此我将models.ManyToManyField(Gallery)models.ManyToManyField(Image)放在两个类中

出现错误的原因:

line 22, in Image     in_gallery = models.ManyToManyField(Gallery)
NameError: name 'Gallery' is not defined

3 个答案:

答案 0 :(得分:1)

Gallery模型放在Image

之上

<强>实施例

from django.db import models
from django.urls import reverse
from django.contrib.auth.models import User
from userprofiles.models import UserProfile
# Create your models here.

import os

class Category (models.Model):
    name = models.CharField(max_length=100)
    def __str__(self):
        return self.name

class Gallery(models.Model):
    name = models.CharField(max_length=100)
    have_images = models.ManyToManyField(Image)

    def __str__(self):
        return self.name

class Image(models.Model):
    owner = models.ForeignKey(UserProfile, on_delete=models.CASCADE)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    in_gallery = models.ManyToManyField(Gallery)
    title = models.CharField(max_length=100)
    def __str__(self):
        return self.title



class ImageInGallery (models.Model):
    image = models.ForeignKey(Image)
    gallery = models.ForeignKey(Gallery)

答案 1 :(得分:0)

ImageGallery之间存在重复关系。

class Image(models.Model):
    in_gallery = models.ManyToManyField(Gallery)

class Gallery(models.Model):
    have_images = models.ManyToManyField(Image)

您只需要定义其中一个字段,然后就可以像docs一样对其进行描述。

如果删除字段Gallery.have_images,则可以:

# list all galleries a image is part of
image_instance.in_gallery.all()

# list all images from a gallery
gallery_instance.image_set.all()

答案 2 :(得分:0)

只需按照您想要的方式保留您的结构,并将模型名称放在引号内 像:

have_images = models.ManyToManyField("Image")

如果模特在另一个应用程序中,请使用该应用程序的名称 实施例

have_images = models.ManyToManyField("app_name.Image")