You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django & Pandas:如何在DataFrame中获取选项值而非选项标签

Got it, let's sort this out—you want the actual integer values (like 1 or 2) from your Django model's choices field in your Pandas DataFrame, not the human-readable labels. Here are a couple of straightforward fixes:

Solution 1: Use values() to fetch raw database values directly

The simplest approach is to leverage Django's values() method on your QuerySet. This returns a list of dictionaries where each key maps to a field name, and the value is the raw data stored in the database (so your status field will be the integer you expect, not the label).

import pandas as pd
from my_app.models import Entry

# Fetch raw field values as dictionaries
queryset = Entry.objects.values('status', 'status_date', 'contents')
# Convert the QuerySet to a Pandas DataFrame
df = pd.DataFrame(list(queryset))

This will immediately give you the integer values for status in your DataFrame.

Solution 2: Extract values from model instances (if you need full instance data)

If you're working with a QuerySet of full Entry instances (and don't want to switch to values()), you can explicitly pull the raw status value when building your DataFrame. Here's how:

entries = Entry.objects.all()
# Build a list of dictionaries with the fields you need, explicitly accessing the status value
data = [
    {
        'status': entry.status,  # This grabs the raw integer from the database
        'status_date': entry.status_date,
        'contents': entry.contents
    }
    for entry in entries
]
df = pd.DataFrame(data)

If you also want to include the human-readable label alongside the integer value (for clarity), you can add that using Django's built-in get_status_display() method:

data = [
    {
        'status': entry.status,
        'status_label': entry.get_status_display(),  # Returns 'Status one' or 'Status two'
        'status_date': entry.status_date,
        'contents': entry.contents
    }
    for entry in entries
]
df = pd.DataFrame(data)

Why you were seeing labels instead of values

Most likely, you were accidentally using get_status_display() somewhere (either in a values_list call or when constructing your DataFrame), or you were converting model instances directly without explicitly accessing the status field. Remember: accessing entry.status gives you the raw stored integer, while entry.get_status_display() returns the human-friendly label.

内容的提问来源于stack exchange,提问作者Barranka

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:30:12