我试图纠正这个Django对象设置错误,但它失败了

时间:2016-09-30 07:08:23

标签: python django

from django.db import models


class Gallery(models.Model):
    Title = models.CharField(max_length=250)
    Category = models.CharField(max_length=250)
    Gallery_logo = models.CharField(max_length=1000)

    def __str__(self):
        return self.Title + '_' + self.Gallery_logo


class Picture (models.Model):
    Gallery = models.ForeignKey(Gallery, on_delete=models.CASCADE)
    Title = models.CharField(max_length=250)
    Artist = models.CharField(max_length=250)
    Price = models.CharField(max_length=20)

    def __str__(self):
        return self.Title

我一直收到这个错误:

Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: 'Gallery' object has no attribute 'pic_set'

我正在使用Pycharm 2016,我刚开始自学Django。

1 个答案:

答案 0 :(得分:1)

由于您刚开始学习django,我要指出字段名称应以小写字母开头。 (使用大写不是错误,但它令人困惑,而不是标准)

class Gallery(models.Model):
    title = models.CharField(max_length=250)
    category = models.CharField(max_length=250)
    gallery_logo = models.CharField(max_length=1000)

    def __str__(self):
        return self.Title + '_' + self.Gallery_logo


class Picture (models.Model):
    gallery = models.ForeignKey(Gallery, on_delete=models.CASCADE)
    title = models.CharField(max_length=250)
    artist = models.CharField(max_length=250)
    price = models.CharField(max_length=20)

现在,如上所述定义外键关系。每个图库都有一个picture_set,该名称来自您选择的模型名称,在本例中为Picture