Joe Kasedde Joe Kasedde - 2 months ago 6
Python Question

I have tried to correct this Django Object set error but it has failed please help me out

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


i keep getting this error

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


Am using Pycharm 2016 and i just begun self learning Django yesterday

Answer

Since you have just started to learn django , let me point out that field names should begin with a lower case letter. (It's not an error to use upper case but it's confusing and not the standard)

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)

Now when you define the foreign key relationship as above. Each Gallery instead has a picture_set that name come from the model name you have chosen which in this case is Picture

Comments