我无法访问模板中的预取相关对象,smb能帮助吗
views.py
def support(request, pk=None):
...
else:
list_support_tickets = sorted(
chain(
SupportTickets.objects.filter(Q(status=0) | Q(status=1), requester=request.user).prefetch_related('reply_relation'), #Can't iter object
), key=attrgetter('creation_date'), reverse=True
)
paginator = Paginator(list_support_tickets, 10)
page = request.GET.get('page')
support_tickets = paginator.get_page(page)
args = {'support_tickets': support_tickets,
'form': form
}
print(list_support_tickets)
return render(request, template, args)
在我的模板上,我做以下操作:
{% for support_ticket in support_tickets %}
...
{% for reply in support_ticket.reply_relation %}
<span class="font-size-small">We have a query, yeah</span>
{% endfor %}
{% endfor %}
但我无法在这里获得查询,错误:
TypeError:"GenericRelatedObjectManager"对象不可迭代
models.py
class SupportTicketMessages(models.Model):
content_type = models.ForeignKey(ContentType, limit_choices_to=referential_models, on_delete=models.CASCADE)
object_id = models.CharField(max_length=36)
content_object = GenericForeignKey('content_type', 'object_id')
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='support_ticket_reply_author', verbose_name='Author', blank=True)
reply = models.TextField(verbose_name="Reply Content", max_length=2000)
date = models.DateTimeField(auto_now_add=True, blank=False)
class SupportTickets(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True)
ticket_id = models.IntegerField(default=ticket_id_generator, unique=True, blank=False, null=False, editable=False)
requester = models.ForeignKey(User, on_delete=models.CASCADE, null=False, blank=False)
category = models.IntegerField(choices=TICKET_CATEGORY, verbose_name='Ticket Category')
subject = models.CharField(max_length=40)
problem_description = models.TextField(max_length=5000)
status = models.IntegerField(choices=STATUS_OF_TICKET, verbose_name='Ticket Status', default=0)
reply_relation = GenericRelation(SupportTicketMessages, related_query_name='reply_relation')
creation_date = models.DateTimeField(auto_now_add=True, null=True)
提前感谢
support_ticket.reply_relation
是管理器,而不是QuerySet
,因此您不能对其进行迭代,您可以使用.all()
[Django-doc]来迭代此:
{% for support_ticket in support_tickets %}
…
{% for reply_relation in support_ticket.reply_relation.all%}
…
{% endfor %}
{% endfor %}