如何强制这个对象只有一个布尔attr设置为true? [英] how to enforce that object is only with a boolean attr set to true?

查看:123
本文介绍了如何强制这个对象只有一个布尔attr设置为true?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

Django中的Unique BooleanField值?

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

on a photograph model i want to choose it as the photograph that is the cover image for a gallery on a page that lists multiple galleries.

我写了以下代码,但它看起来像ive创建一个循环

i wrote the following code, but it looks like ive created a loop

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()

whats heppening是

whats heppening is


  • 上传图片,将其设置为
    portfolio_image

  • 代码遍历并点击if语句

  • popula tes其他人,得到o.save(),最终运行完全相同的
    代码,我已经定义。

循环!

我如何解决这个问题?

推荐答案

我想你应该在其他地方存储 testimonial_image ,它应该等于 id 需要的照片对象。

I think you should store testimonial_image somewhere else, and it should equal id of needed Photograph object.

这篇关于如何强制这个对象只有一个布尔attr设置为true?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆