简体   繁体   English

如何遍历 ManyToManyField 中的 Django model 项

[英]How to iterate through Django model items in a ManyToManyField

Brand new to Django/Python and thought I'd start by building a simple blog app.全新的 Django/Python 并认为我会从构建一个简单的博客应用程序开始。 I would like the User to be able to post book references that include the book name and a link to the book.我希望用户能够发布包含书名和书的链接的书籍参考。

My current References class in my models.py looks like this:我的models.py中当前的References class 如下所示:

class References(models.Model):
    link = models.URLField(max_length=150, default=False)
    title = models.CharField(max_length=100, default=False)

    def __str__(self):
        return self.title

and my Post class looks like this:我的Post class 看起来像这样:

class Post(models.Model):
    title = models.CharField(max_length=31)
    content = models.TextField()
    thumbnail = models.ImageField()
    displayed_author = models.CharField(max_length=25, default=True)
    shortquote = models.TextField()
    reference_title = models.ManyToManyField(References)
    publish_date = models.DateTimeField(auto_now_add=True)
    last_updated = models.DateTimeField(auto_now=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    slug = models.SlugField()

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse("detail", kwargs={
            'slug': self.slug
        })

    def get_love_url(self):
        return reverse("love", kwargs={
            'slug': self.slug
        })

    @property
    def comments(self):
        return self.comment_set.all()

    @property
    def get_comment_count(self):
        return self.comment_set.all().count()

    @property
    def get_view_count(self):
        return self.postview_set.all().count()

    @property
    def get_love_count(self):
        return self.love_set.all().count()

I understand that i'm only returning the title in my References class, I've tried returning self.title + self.link but this gives me both the title and link together when being called in the template.我知道我只是在我的参考文献 class 中返回title ,我试过返回self.title + self.link但这在模板中调用时同时给了我标题和链接。

My template calling the references class looks like this:我调用引用 class 的模板如下所示:

{% for title in post.reference_title.all  %}
        <a href="{{ link }}">
           <li>{{ title }}</li>
        </a>
{% endfor %}

I've tried a combination of different things in order to get the link AND title to render independently as shown in the template, but the issue comes with knowing how to display different items from a class through a ManyToManyField .我已经尝试了不同的组合,以便让链接和标题独立呈现,如模板中所示,但问题在于知道如何通过ManyToManyField显示 class 中的不同项目。 Any help on this would be great as I do believe it's just something I haven't learnt yet.对此的任何帮助都会很棒,因为我相信这只是我还没有学到的东西。 Thanks in advance!提前致谢!

title is not the title, it is a References object, it is only because you implemented __str__ to return the title, that {{ title }} , will indeed render the .title attribute of that References object. title不是标题,它是References object,只是因为您实现__str__以返回标题, {{ title }}确实会呈现该References object 的.title属性。

You thus iterate over it, and access the attribute:因此,您对其进行迭代,并访问该属性:

{% for reference in post.reference_title.all  %}
    <a href="{{ reference.link }}">
        <li>{{ reference }}</li>
    </a>
{% endfor %}

You thus can replace {{ reference }} with {{ reference.title }} here, although the two are equivalent because the __str__ returns the title.因此,您可以在此处将{{ reference }}替换为 { {{ reference.title }} ,尽管两者是等价的,因为__str__返回标题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何按排序顺序遍历Django ManyToManyField? - How to iterate through a Django ManyToManyField in a sorted order? 如何在django-jinja项目中的ManyToManyField中进行迭代? - How do I iterate through a ManyToManyField in django-jinja project? Django Admin-通过模型过滤ManyToManyField - Django Admin - Filter ManyToManyField with through model 使用 Django 通过模型字段定义 ManyToManyField 的顺序 - Define an order for ManyToManyField by through model field with Django Django:从ManyToManyField访问“通过”模型 - Django: Access “through” model from ManyToManyField 如何遍历 model 中的两个项目并使用 Django 在现场显示? - how do you iterate through two items in a model and display on site using Django? Django:如何获取模型字段是否为ManyToManyField - Django: how to get model field is ManyToManyField or not Django:有没有办法在与包含ManyToManyField的模型不同的应用程序中的ManyToManyField中使用“直通”模型? - Django: Is there a way to have the “through” model in a ManyToManyField in a different app to the model containing the ManyToManyField? ManyToManyField通过一个抽象模型 - ManyToManyField with through on an abstract model 在Django admin中验证ManyToManyField项目(使用中间模型)的数量 - Validating number of ManyToManyField items (with intermediate model) in Django admin
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM