为什么我无法在 DJANGO 中获取预取的相关对象?
我想为每个使用预取相关的画廊获取缩略图= True 的 midia 。
class Midia(Base):
galeria = models.ForeignKey(Galeria, on_delete=models.CASCADE, related_name= "midias")
thumbnail = models.BooleanField('Thumbnail ', default=False)
video_thumbnail = models.URLField(blank = True)
imagem = StdImageField(upload_to='midias/', blank=True, delete_orphans=True)
class Galeria(Base):
titulo = models.CharField('Título', max_length=100)
descricao = models.TextField('Descrição', blank= True)
我在视图中使用此代码来完成此操作:
galerias = Galeria.objects.prefetch_related(Prefetch('midias', queryset= Midia.objects.filter(thumbnail = True))).all()
在 HTML 中使用此代码:
{% for galeria in galerias %}
{% with thumbnail=galeria.midias.first %}
{% if thumbnail %}
{% if thumbnail.imagem %}
<img src="{{ thumbnail.imagem.url }}" alt="" >
{% else %}
<img src="{{ thumbnail.video_thumbnail }}" alt="">
{% endif %}
{% else %}
<img src="generic image" alt="" >
{% endif %}
{% endwith %}
但是为什么当我尝试执行此操作时:
{% with thumbnail=galeria.midias %}
它返回 None。检查数据库中的 sqls 命中,galeria.midias.first 没有出现(预取正在工作并且仅返回缩略图 = True 的 midia)。为什么当我使用 galeria.midias 时它返回 None ?
I want to get the midia with the thumbnail = True for every galeria using the prefetch related.
class Midia(Base):
galeria = models.ForeignKey(Galeria, on_delete=models.CASCADE, related_name= "midias")
thumbnail = models.BooleanField('Thumbnail ', default=False)
video_thumbnail = models.URLField(blank = True)
imagem = StdImageField(upload_to='midias/', blank=True, delete_orphans=True)
class Galeria(Base):
titulo = models.CharField('Título', max_length=100)
descricao = models.TextField('Descrição', blank= True)
I did it using this code in the view:
galerias = Galeria.objects.prefetch_related(Prefetch('midias', queryset= Midia.objects.filter(thumbnail = True))).all()
And this in the HTML:
{% for galeria in galerias %}
{% with thumbnail=galeria.midias.first %}
{% if thumbnail %}
{% if thumbnail.imagem %}
<img src="{{ thumbnail.imagem.url }}" alt="" >
{% else %}
<img src="{{ thumbnail.video_thumbnail }}" alt="">
{% endif %}
{% else %}
<img src="generic image" alt="" >
{% endif %}
{% endwith %}
But why when i try to do this:
{% with thumbnail=galeria.midias %}
It returns None. Checking the sqls hits in the database the galeria.midias.first does not appear (the prefetch is working and returning only the midia with the thumbnail = True). Why when i use galeria.midias it returns None?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
因为 midias 是一个查询集。不是一个物体。所以你必须迭代它。
Because midias is a queryset. Not an object. So you have to iterate through it.