我试图循环遍历一个对象,并将结果存储在一个列表中,这样我就可以在django模板中使用它并显示它我试图复制我的代码中其他地方的一些东西来满足我的需要,但它不起作用。我试着复制这个
{% for tag in instance.tags.all %}
{{ tag.post_set.all }}
{% endfor %}
这将返回一个块中的所有内容。我想能循环通过所以我试过了
links = []
for t in tag:
links.append(
t.post_set.all()
)
mylink = links
context = {
"title": "detail ",
"instance": instance,
"hops": mylink
}
但没用。从循环中提取结果并将其存储在一个列表中的正确语法是什么,然后可以在模板中使用欢迎一切帮助或建议
编辑:
我的观点
def post_detail(request, slug=None):
instance = get_object_or_404(Post, slug=slug)
tag = instance.tags.all
links = []
for t in tag:
links.append(
t.post_set.distinct()
)
share_string = quote_plus(instance.content)
tag = instance.tags.all()
context = {
"title": "detail ",
"instance": instance,
"share_string": share_string,
"tag": tag
}
return render(request, "posts/post_detail.html", context)
class Tag(models.Model):
title = models.CharField(max_length=250)
slug = models.SlugField(max_length=200, unique=True)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("posts:tag_index", kwargs={"slug": self.slug})
class Meta:
ordering = ["-timestamp"]
class Post(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
slug = models.SlugField(unique=True)
title = models.CharField(max_length=120)
image = models.ImageField(upload_to=upload_location, null=True, blank=True,
width_field="width_field",
height_field="height_field")
height_field = models.IntegerField(default=0)
width_field = models.IntegerField(default=0)
content = models.TextField()
draft = models.BooleanField(default=False)
publish = models.DateField(auto_now=False, auto_now_add=False)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
tags = models.ManyToManyField(Tag)
objects = PostManager()
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("posts:detail", kwargs={"slug": self.slug})
class Meta:
ordering = ["-timestamp"]
def create_slug(instance, new_slug=None):
slug = slugify(instance.title)
if new_slug is not None:
slug = new_slug
qs = Post.objects.filter(slug=slug).order_by("-id")
exists = qs.exists()
if exists:
new_slug = "%s-%s" % (slug, qs.first().id)
return create_slug(instance, new_slug=new_slug)
return slug
def pre_save_post_receiver(sender, instance, *args, **kwargs):
if not instance.slug:
instance.slug = create_slug(instance)
pre_save.connect(pre_save_post_receiver, sender=Post)
这就是我所拥有的
最佳答案
最好对你想要的帖子进行一次查询。
links = Post.objects.filter(link__tag__instancemodel=instance)
其中
instancemodel
是任何模型的名称。关于python - 如何遍历结果并将其存储在列表中,以便可以在Django模板中使用它们,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35136179/