Model.objects.filter([foreign table])。update()

时间:2013-11-21 01:39:32

标签: python django

在这种情况下,如何使用真正的Django代码更改[book must etc...]

Book.objects.filter(processed=True, [book must have all the volumes belonging to it with property is_file_processed set to True]).update(status="PU")

型号:

class Book(models.Model):
    title = models.CharField(max_length=100, blank=True)
    ...


class Volume(models.Model):
    file = models.FileField(...)
    ...
    is_file_processed = models.BooleanField(default=False)
    book = models.ForeignKey(Book)

2 个答案:

答案 0 :(得分:1)

docs。我认为这可行。

class Book(models.Model):
    title = models.CharField(max_length=100, blank=True)
    ...


class Volume(models.Model):
    file = models.FileField(...)
    ...
    is_file_processed = models.BooleanField(default=False)
    book = models.ForeignKey(Book, related_name='volumes')

Book.objects.filter(processed=True, volumes__is_file_processed=True).update(status="PU")

答案 1 :(得分:1)

由于处理了所有卷的所有书籍的集合等于这样的结果:所有具有至少一个卷处理的书籍的集合减去了具有未处理卷的所有书籍的集合:

Book.objects.filter(processed=True, volume__is_file_processed=True).exclude(volume__is_file_processed=False).update(status="PU")
# Or    
Book.objects.exclude(volume__is_file_processed=False).filter(processed=True, volume__is_file_processed=True).update(status="PU")