如何强制该对象仅使用布尔attr设置为true?

时间:2011-05-20 13:07:26

标签: django django-models

  

可能重复:
  Unique BooleanField value in Django?

在照片模型上我想选择它作为照片,该照片是列出多个画廊的页面上的画廊的封面图像。

我写了下面的代码,但看起来我已经创建了一个循环

class Photograph(models.Model):
    project = models.ForeignKey(Project)
    description = models.TextField(max_length=5000, default=False)
    image = models.ImageField(upload_to="photographs/")
    thumb = models.ImageField(upload_to="photographs/", blank=True, help_text="Ignore this field, it will autopopulate")
    thumbnail = models.CharField(max_length=250, blank=True)
    filename = models.CharField(max_length=100, default=False, help_text="Ignore this field, it will autopopulate")
    portfolio_image = models.BooleanField(default=False, help_text="Do you want this image to appear as the portfolio image?")
    date_added = models.DateTimeField('date published')

def save(self):
    # get filename for use later
    filename, extension = os.path.splitext(self.image.name)
    self.filename = slugify(filename)
    self.thumbnail = filename+"-t.jpg"

    # is this the testimonial image, if so, unselect other images
    if self.testimonial_image is True:
        others = Photograph.objects.filter(project=self.project).filter(testimonial_image=True)
        pdb.set_trace()
        for o in others:
            o.testimonial_image = False
            o.save()

什么是heppening

  • 上传图片,将其设置为 portfolio_image
  • 代码贯穿并命中if语句
  • 填充其他人,获取o.save()并最终运行完全相同 我定义的代码。

环!

我如何绕过这个?

1 个答案:

答案 0 :(得分:2)

我认为你应该将testimonial_image存储在其他地方,它应该等于所需id个对象的Photograph