【问题标题】:How to return Django model in a url?如何在 url 中返回 Django 模型?
【发布时间】:2021-09-11 15:45:35
【问题描述】:

我希望我的 Django 模型可以通过 http://localhost:8000/teams 访问

models.py:

from typing import Any
from django.db import models

class Team(models.Model):
    top_id = models.CharField(max_length=20, unique = True)
    
    def __str__(self):
        return self.top_id

urls.py:

from django.urls import path
from backend import views,models

urlpatterns = [
    path("teams/", models.Team, name="teams"),
    path("", views.home, name = "home"),
]

我知道该对象没有“get”属性。我该如何设置?我试过 getattribute 但似乎没有用。 我想要一个这样的 url,这样我以后可以在我的 react 应用程序中通过 axios 下载模型。

【问题讨论】:

    标签: python django django-models axios url-pattern


    【解决方案1】:

    为此,您需要创建一个ListView,它将列出所有团队。

    这方面的文档是here

    基本上你的视图可能是这样的;

    from django.views.generic.list import ListView
    
    from backend.models import Team
    
    
    class TeamListView(ListView):
    
        model = Team
        paginate_by = 100  # if pagination is desired 
    

    你的网址变成了;

    from django.urls import path
    from backend.views import TeamListView
    
    urlpatterns = [
        path("teams/", TeamListView.as_view(), name="teams"),
        path("", views.home, name = "home"),
    ]
    

    这里有一个很好的站点,可以查看与基于类的视图相关的所有内容; http://ccbv.co.uk/

    【讨论】:

    猜你喜欢
    • 2020-11-06
    • 2010-10-07
    • 2011-09-09
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多