Django OneToOneField错误

时间:2013-03-14 05:46:18

标签: django

我的应用程序允许用户创建电路板并添加图片。

我的目标是尝试从其图片列表中找到一张带有主要图片的电路板。我会尽力解释我的情况。我试着用每块电路板显示主图片从它的图片列表中可以看出,当用户创建一个电路板时,他可以将图片添加到他的电路板上,现在我想将其中一张图片与电路板一起显示。 我给你举个例子enter image description here

所以我尝试使用OneToOneField将主要图片与电路板相结合,我得到了这个错误 创建板时,pet_board.picture_id可能不为NULL

我的models.py

class Board(models.Model):
    user = models.ForeignKey(User)
    name = models.CharField(max_length=100)
    picture = models.OneToOneField('Picture',related_name='picture',blank=True,null=True)
    def __unicode__(self):
        return self.name

class Picture(models.Model):
    user = models.ForeignKey(User)
    board = models.ForeignKey(Board ,related_name='lo')

    image = models.FileField(upload_to="images/",blank=True,null=True)
    description = models.TextField()
    def __unicode__(self):
        return self.description

2 个答案:

答案 0 :(得分:2)

<强> models.py

class Board(models.Model):
    user = models.ForeignKey(User)
    name = models.CharField(max_length=100)

class Picture(models.Model):
    user = models.ForeignKey(User)
    board = models.ForeignKey(Board)
    image = models.FileField(upload_to="images/",blank=True,null=True)
    description = models.TextField()
    is_primary = models.BooleanField(default=False)

    def __unicode__(self):
        return self.description

<强> views.py

def index(request):
    obj_board = Board.objects.get(user=request.user)
    obj_image = obj_board.picture_set.filter(is_primary=True)
    print obj_image.image.url  # output url in dev-server for tests
    # ... do something and return httpresponse

答案 1 :(得分:2)

class Board(models.Model):
    user = models.ForeignKey(User)
    name = models.CharField(max_length=100)
    picture = models.OneToOneField('Picture',related_name='picture',blank=True,null=True)

    def __unicode__(self):
        return self.name

    def primary_picture(self): 
        return Picture.objects.filter(board=self, is_primary=True)

    def ordinary_picture(self): 
        return Picture.objects.filter(board=self, is_primary=False)

class Picture(models.Model):
    user = models.ForeignKey(User)
    board = models.ForeignKey(Board ,related_name='lo')
    image = models.FileField(upload_to="images/",blank=True,null=True)
    description = models.TextField()
    is_primary = models.BooleanField(default=False)

    def __unicode__(self):
        return self.description

{% for b in person.get_board %}  
    My Primary Pictures:
    {% for primary in b.primary_picture %}
        <img src="{{ primary.image.url }}">
    {% endfor %}

    My Ordinary Pictures:
    {% for ord in b.ordinary_picture %}
        <img src="{{ ord.image.url }}">
    {% endfor %}
{% endfor %}