【问题标题】:Looping through two models that contain lists and are connected Django循环遍历两个包含列表并连接的模型 Django
【发布时间】:2020-12-18 21:37:40
【问题描述】:

我是 Python/Django 的初学者,我目前正在尝试制作一个用于制作收集日志的基本应用程序。首先,用户选择一个类别,然后在该类别下插入对象。

我在 models.py 中有两个类,代码如下:

class object_category(models.Model):
"""This class contains the users different categories"""
CATEGORY_CHOICES = [
    ('category1', 'category1'),
    ('category2', 'category2'),
    ('category3', 'category3'),
]
"""Plural for multiple categories"""
class Meta:
    verbose_name_plural = 'Categories'
    
"""Returns the above stated choices"""
category = models.CharField(max_length=50, choices=CATEGORY_CHOICES)
def __str__(self):
    return self.category

class object_name(models.Model):
"""This class contains the object name that is housed within a certain category"""
"""Links the object to one of the chosen categories"""
category = models.ForeignKey(object_category, on_delete=models.CASCADE)

# Placeholder for connection with a plant database API
object = models.CharField(max_length=50)

"""Return the object input from the user"""
def __str__(self):
    return self.object

这里是views.py代码:

def collection(request):
"""The page that opens the collection of objects"""
object_category = Object_category.objects.order_by('category')
object_name = Object_name.objects.order_by('object')

context = {
    'object_category': object_category,
    'object_name': object_name
}

return render(request, 'plntz_main/collection.html', context)

最后这是我的 html 文档代码:

{% for category in object_category %}
    {% for object in object_name %}
        <h3>{{ category }}</h3>
            <li>{{ object }}</li>
{% empty %}
    <li>No category has been added yet.</li>
    {% endfor %}
{% endfor %}

这会显示类别和对象,但它们没有链接。

我要显示的是:

  • 用户选择的类别
  • 该特定类别中的每个对象

谁能解释我是如何修改代码得到这个结果的?

对不起,这是一团糟。我是新手,这是我第一次尝试一个项目,也是我在 stackoverflow 上的第一个问题。

谢谢!

【问题讨论】:

    标签: python django


    【解决方案1】:

    您应该先阅读文档并逐步完成一些基本教程,在此处阅读有关过滤查询集Django Querysets 的文档。

    你可以这样做来实现它

    首先,将related_name 设置为您的类别外键

    class object_name(models.Model):
    """This class contains the object name that is housed within a certain category"""
    """Links the object to one of the chosen categories"""
    category = models.ForeignKey(object_category, on_delete=models.CASCADE, related_name='object_names')
    
    # Placeholder for connection with a plant database API
    object = models.CharField(max_length=50')
    
    """Return the object input from the user"""
    def __str__(self):
        return self.object
    

    然后在你的views.py中你只需要这样做

    object_categories = Object_category.objects.all().order_by('category')
    
    context = {
        'object_categories': object_categories,
    }
    

    然后我你的模板文件做这样的事情:

        {% for category in object_categories %}
            <h3>{{ category }}</h3>
            {% for name in object_categories.object_names.all %}
                    <li>{{ name.object }}</li>
            {% endfor %}
        {% empty %}
            <li>No category has been added yet.</li>
        {% endfor %}
    

    我没有测试,你自己试试看是否有效:)

    【讨论】:

    • 我已经尝试了代码 - 我得到了以下结果(我停止隐藏我的类别名称,因为它与 .objects 超级混淆): Collection: Houseplants Outdoors Succulents 所以基本上我得到了类别,但不是类别中植物的名称。 (我在管理模块中添加了一些)。我是否在新帖子中再次粘贴代码或最好的方法是什么? @拜瓦拉斯
    • 抱歉,我没有真正理解您遇到的问题。如果我上面的代码有效,请将其标记为正确答案并为新问题打开一个新答案。您可以在此处粘贴链接,我会帮助您:) @de_l3ns
    • 感谢您的迅速回复。就像你说的那样,我提出了一个新问题并将这个问题解决了:)。这是网址:stackoverflow.com/questions/63676460/…@baivaras
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多