Django从不同层面获取数据

2024-04-20 10:36:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个Django项目,其结构如下:在主页中,有许多主题。在每个主题中,都有许多与之相关的条目。主题和条目信息可以作为访问者的输入。现在我需要按组从条目中获取数据。例如,对于主题“水果”,条目包括“苹果”、“梨”、“香蕉”;主题“运输”,条目包括“汽车”、“飞机”。你知道吗

我需要获得的数据是:

[[(u'apple',), (u'pear',), (u'banana',)], [(u'car',), (u'plane',)]]. 

如何在函数中编辑编码查看.py?我提议如下:

def button_view(request):
    import sys
    topics = Topic.objects.filter(owner=request.user).order_by("date_added")
    a_content_list = []
    for a in topics
        entries = Entry.objects.get(topic = a)
        a_content_list.append(entries)

这是我在这里设置的型号.py地址:

class Topic(models.Model):
    text = models.CharField(max_length=200)
    date_added = models.DateTimeField(auto_now_add=True)
    owner = models.ForeignKey(User, on_delete=models.CASCADE)   
    def _str_(self):
        return self.text

class Entry(models.Model):
    topic = models.ForeignKey(Topic, on_delete=models.CASCADE)
    text = models.TextField()
    date_added = models.DateTimeField(auto_now_add=True)
    class Meta:
        verbose_name_plural = 'entries'

    def _str_(self):
        return self.text[:50] + "..."
        #on_delete=models.CASCADE,

a\内容\列表是我想要的吗?你知道吗


Tags: textpyself主题addeddatetopicon
1条回答
网友
1楼 · 发布于 2024-04-20 10:36:27

编辑:我误解了要求。你知道吗

要获取条目列表,每个列表包含特定主题的条目,请执行以下操作:

entry_values = [
    [entry.value for entry in topic.entries.all()]
    for topic in Topic.objects.filter(owner=request.user).order_by("date_added")
]

这假设您在Entry.topicForeignKey定义中将^{}设置为“entries”。你知道吗

相关问题 更多 >