2

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

我的目标是尝试将板与图片列表中的主图片相关联。我会尽力解释我的情况。我正在尝试在每个板上显示图片列表中的主图片,因为当用户创建板时他可以将图片添加到他的板上,现在我想将其中一张图片与板显示相关联。我给你举个例子在此处输入图像描述

因此,我尝试使用 OneToOneField 将板与主图片相关联,但在创建板时出现此错误 pet_board.picture_id may not be NULL

我的模型.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
4

2 回答 2

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 %}
于 2013-03-14T08:14:23.543 回答
2

模型.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

视图.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
于 2013-03-14T07:50:58.220 回答