Django-批注未显示在模板中

时间:2018-09-15 10:48:20

标签: django annotations django-views

我正在尝试在模板中显示注释。我有两个模型(model1和model2),我想显示与model1相关的model2的数量。

这是我的views.py:

def model2_count(request, pk):
    model2count = models.Model1.objects.filter(pk=model1.pk).annotate(title_count=Count(‘model2__title'))
    return render(request, 'model1/_model1.html', {‘m2c’: model2count})

这是模板(model1 / _model1.html):

我尝试过:

{% for object in m2c %}</h3>
    {{ object.title }}
    {{ object.title_count }}
{% endfor %}

并尝试了此操作

{% if m2c.title_count %}
    {{ m2c.title_count }}
{% endif %}

这几天我一直在梳头,无法弄清。以下内容基本上无济于事:

令人沮丧的是,我什至不能说为什么应用这些解决方案无效。

感谢任何输入。

此外,这是我的模型,其中所有的BS都已取出。

class Publication(models.Model):
    title = models.CharField(max_length=150, unique=False, blank=False)
    contributors_note = models.TextField(max_length=300, blank=False)
    website = models.URLField()
    publisher = models.CharField(max_length=250, unique=False)
    publication_date = models.DateField(default=datetime.date.today)
    slug = models.SlugField(allow_unicode=True, unique=False)

    content_type = models.CharField(max_length=100, unique=False)# In this field user's define the type of content (blog, newspaper article, publication etc)
    research_type = models.CharField(max_length=100, unique=False)# In this field user's define whether the research is based on primary or secondary research
    user = models.ForeignKey(Current_user, related_name="publication")
    created_at = models.DateTimeField(auto_now_add=True)
    last_updated = models.DateTimeField(auto_now=True)
    category = models.ForeignKey(Category, related_name="publication",null=True, blank=False)

    comment = models.TextField()


    def __str__(self):
        return self.title

    def save(self, *args, **kwargs):
        self.slug = slugify(self.title)
        super().save(*args, **kwargs)

    def get_absolute_url(self):
        return reverse(
            "publication:single",
            kwargs={
                "username": self.user.username,
                "pk": self.pk
            }
        )

    class Meta:
        ordering = ["-created_at"]


class Assessment(models.Model):
    title = models.CharField(max_length=150, unique=False, blank=False)
    publication = models.ForeignKey('publication.Publication', on_delete=models.CASCADE, related_name='assessment')
    analyst = models.ForeignKey(Current_user, null=True, blank=True, related_name="assessment")
    created_at = models.DateTimeField(auto_now_add=True)
    approved_comment = models.BooleanField(default=False)


    key_finding1 = models.TextField(max_length=300)
    key_finding2 = models.TextField(max_length=300)
    key_finding3 = models.TextField(max_length=300)

    ratings_range = (
    ('1', 'Very Weak'),
    ('2', 'Weak'),
    ('3', 'Moderate'),
    ('4', 'Strong'),
    ('5', 'Very Strong'),
    )

    content_rating_1 = models.CharField(max_length=1, choices=ratings_range)
    content_rating_1_comment = models.TextField(max_length=300)
    content_rating_2 = models.CharField(max_length=1, choices=ratings_range)
    content_rating_2_comment = models.TextField(max_length=300)
    content_rating_3 = models.CharField(max_length=1, choices=ratings_range)
    content_rating_3_comment = models.TextField(max_length=300)
    content_rating_4 = models.CharField(max_length=1, choices=ratings_range)
    content_rating_4_comment = models.TextField(max_length=300)
    content_rating_5 = models.CharField(max_length=1, choices=ratings_range)
    content_rating_5_comment = models.TextField(max_length=300)

    source_rating_1 = models.CharField(max_length=1, choices=ratings_range)
    source_rating_1_comment = models.TextField(max_length=300)
    source_rating_2 = models.CharField(max_length=1, choices=ratings_range)
    source_rating_2_comment = models.TextField(max_length=300)
    source_rating_3 = models.CharField(max_length=1, choices=ratings_range)
    source_rating_3_comment = models.TextField(max_length=300)
    source_rating_4 = models.CharField(max_length=1, choices=ratings_range)
    source_rating_4_comment = models.TextField(max_length=300)
    source_rating_5 = models.CharField(max_length=1, choices=ratings_range)
    source_rating_5_comment = models.TextField(max_length=300)


    def approve(self):
        self.approved_comment = True
        self.save()

    def __str__(self):
        return self.title

    class Meta:
        ordering = ["-created_at"]

2 个答案:

答案 0 :(得分:0)

仅使用字段名称(即 [{'question': "What is the meaning of 'واد' ?", 'transliteration': 'walid', 'answer': 'boy'}, {'question': "What is the meaning of 'بنت' ?", 'transliteration': 'bint', 'answer': 'girl'}, {'question': "What is the meaning of 'رخل' ?", 'transliteration': 'ragul', 'answer': 'man'}, {'question': "What is the meaning of 'ست' ?", 'transliteration': 'sit', 'answer': 'woman'}] What is the meaning of 'واد' ? What is the meaning of 'بنت' ? What is the meaning of 'رخل' ? What is the meaning of 'ست' ? [{'question': "What is the meaning of '2test1'?", 'transliteration': 'phonix', 'answer': '21'}, {'question': "What is the meaning of '2test2'?", 'transliteration': 'phonix2', 'answer': '22'}] What is the meaning of '2test1'? What is the meaning of '2test2'? [{'question': "What is the meaning of '3test1'?", 'transliteration': 'phonix', 'answer': '31'}, {'question': "What is the meaning of '3test2'?", 'transliteration': 'phonix2', 'answer': '32'}] What is the meaning of '3test1'? What is the meaning of '3test2'? 而不是model2

来完成第一次聚合)

接下来获得建议使用model2__title.values的带注释列的计数,但不是必需的。

https://docs.djangoproject.com/es/2.1/topics/db/aggregation/#cheat-sheet

values_list

model1 = Model1.objects.get(pk=model1.pk) model2count = ( Model1.objects.annotate(count=Count('model2')) .filter(pk=model1.pk) .values_list('title', 'count', named=True) )

template.html

答案 1 :(得分:0)

我的错误很严重。上面给出的解决方案有效。这是我的最终代码:

views.py

class PublicationDetail(SelectRelatedMixin, generic.DetailView):
model = models.Publication
select_related = ("category", "user")

def get_queryset(self):
    queryset = super().get_queryset()
    return queryset.filter(user__username__iexact=self.kwargs.get("username")).annotate(assessment_count=Count('assessment'))

跟随的新手: -如果您只是发布原始代码而不是尝试变得聪明,那么对于想要帮助您的人(和对您来说更快)的人会更容易。不要不好意思。如果我那样做的话,我会一直节省我们的时间。