Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何循环结果并将其存储在列表中,以便在Django模板中使用它们_Python_Django - Fatal编程技术网

Python 如何循环结果并将其存储在列表中,以便在Django模板中使用它们

Python 如何循环结果并将其存储在列表中,以便在Django模板中使用它们,python,django,Python,Django,我试图循环遍历一个对象,并将结果存储在一个列表中,以便在django模板中使用它并显示它。我试图复制代码中其他地方的内容以满足我的需要,但它不起作用。我试着复制这个 {% for tag in instance.tags.all %} {{ tag.post_set.all }} {% endfor %} 这将在一个块中返回所有内容。我希望能够循环通过它,所以我尝试了这个 links = [] for t in tag: links.append( t.post

我试图循环遍历一个对象,并将结果存储在一个列表中,以便在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)
这就是我所拥有的

为什么在模板中没有内部循环:

{% for tag in instance.tags.all %}
      {% for post in tag.post_set.all %}
          {{ post }}
      {% endfor %}
{% endfor %}

我再回答一个问题。具有正确的模板语法

您应该尽量减少模板中出现的业务逻辑,因为呈现性能已经够差了。将不同的逻辑移到Python代码中。 使用可能对你有用

links = []
for t in tag:
   links.append(
       t.post_set.distinct()
   )
保持模板逻辑基本

只需直接从模型访问和存储标记,并在上下文中返回它们。如果我没有弄错的话,instance.tags应该返回一个查询集,这意味着您可以简单地对标记调用distinct()

您的模板应该类似于:

{% for tag in tags %}
      {{ tag }}
{% endfor %}

最好对您想要的帖子进行一次查询

links = Post.objects.filter(link__tag__instancemodel=instance)

其中
instancemodel
instance
所属的任何型号的名称。

@alexcxe感谢您的回复。按照我想要的方式,我想我可以返回distinct()。Distinct在模板中不起作用我收到一个错误“method”对象不可编辑。这就是我提出的问题。如何将循环结果存储到列表中,以便我可以使用它。我不知道怎么做。好吧,如果你提供了模型结构,可能会更容易回答。将我的答案编辑为可能有帮助的内容?谢谢你尝试帮助我,但这种方式也不起作用。我一直在尝试添加标签和删除标签。对于我添加的每个标签,它都会列出所有连接到它的帖子。使它重复。因此,为每个标记生成一个新列表。我甚至试过set方法。这也不起作用,这就是为什么我想将for循环结果打包到一个列表中,并在模板中迭代它。
links = Post.objects.filter(link__tag__instancemodel=instance)