由于某些文件上传功能,我有非规范化的数据库。用户可以在每个事件和少量图像上发布一个EventComment。图像与评论分开存储。现在我需要连接它们并设置一个每天执行一次的任务。
class EventComment(models.Model):
author = models.ForeignKey('user')
event = models.ForeignKey('event')
class Image(models.Model):
author = models.ForeignKey('user')
event = models.ForeignKey('event')
foo = models.ForeignKey('foo', null=True, blank=True)
我非常不想这样做:
for i in Image.objects.filter(eventcomment__isnull=True):
i.eventcomment = EventComment.objects.get(event=i.event, author=i.author)
i.save()
编写嵌套查询集的正确方法是什么?我试过这种方式,但是我得到DataError:整数的输入语法无效:" event"
Image.objects.filter(eventcomment__isnull=True).update(eventcomment=EventComment.objects.get(event=Value('event'), author=Value('author')))
编辑:
对于这种情况,我应该在try / catch子句中包装queryset:
for i in Image.objects.filter(eventcomment__isnull=True):
try:
i.eventcomment = EventComment.objects.get(event=i.event, author=i.author)
i.save()
exception (EventComment.DoesNotExist, MultipleObjectsReturned):
i.delete()
但是如果我想在一行中写它,在我的情况下会返回MultipleObjectReturned异常可以用F表达式写它:
Image.objects.filter(eventcomment__isnull=True).update(eventcomment=EventComment.objects.get(event=F('event__id'), author=F('author__id')