简体   繁体   English

是否可以为 Pandas 数据框中的每一行创建唯一的 Django 路径?

[英]Is it possible to create a unique Django path for each row in a pandas dataframe?

I have a Django project that takes information in each row of a pandas dataframe and displays the contents on the page.我有一个 Django 项目,它在 Pandas 数据帧的每一行中获取信息并在页面上显示内容。 I'd like to separate each row of the dataframe into its own page with its own unique path.我想将数据框的每一行分成自己的页面,并具有自己的唯一路径。 There are too many rows in the dataframe to hard code each row in the context of the views.py file.数据框中的行太多,无法在 views.py 文件的上下文中对每一行进行硬编码。 How would I go about creating a unique url path for each row?我将如何为每一行创建一个唯一的 url 路径? Is this even possible?这甚至可能吗?

You probably want to do something like embed the row as a parameter in the url您可能想要做一些事情,比如将行作为参数嵌入到 url 中

like喜欢

http://example.com/pandasdata/<row>

In your view your would extract the row from the url and extract only that data from the pandas dataframe and display that.在您看来,您将从 url 中提取该行并仅从 pandas 数据框中提取该数据并显示该数据。

In your application urls.py File Add Following code在您的应用程序urls.py文件中添加以下代码

path('pandasdata/< int:rowid >', views.row)

In your application views.py file, add following code:在您的应用程序 views.py 文件中,添加以下代码:

def row(request, rowid):
  # Add code to extract row and display here

Make sure both place name should be same (rowid)确保两个地名应该相同(rowid)

The answer above is exactly correct and just what I was looking for.上面的答案完全正确,正是我想要的。 I'd just like to elaborate on this for anyone stumbling across this question in the future.我只想为将来遇到这个问题的任何人详细说明这一点。

As stated in the answer, in the urls.py file add the path that allows you extract row information.如答案中所述,在urls.py文件中添加允许您提取行信息的路径。 Something like:就像是:

path("data/<int:row_id>/", views.app)

Then in your views.py file, you'll be able to access the row information like this:然后在您的views.py文件中,您将能够像这样访问行信息:

def func(request, row_id):
    row_id = row_id
    x = row_id
    df1 = df.iloc[x]
    return render(request, "data/app.html", {
        "col1": df1['col1'],
        "col2": df1['col2'],}

Now when you visit a path like http://example.com/data/100/ for example, it will load the row with that index from the dataframe, along with whatever information from the columns that you have set in the context.现在,当您访问像http://example.com/data/100/这样的路径时,它将从数据框中加载具有该索引的行,以及您在上下文中设置的列中的任何信息。 Or if the number is outside the number of rows in your database it will throw you an error.或者,如果该数字超出数据库中的行数,则会引发错误。

Thanks to WombatPM for the original answer!感谢 WombatPM 的原始答案!

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM