首页 > 解决方案 > Python 的 DRF,字段名称“”对模型无效

问题描述

我有以下模型,我要求用户输入。

from django.db import models


# Create your models here.

class PostGDT1AndUAV(models.Model):


    latitude_gdt = models.FloatField(name='Latitude Of GDT 1',
                                     unique=True, max_length=255, blank=False,
                                     help_text="Enter the location's Latitude, first when extracting from Google Maps.",
                                     default=1)
    longitude_gdt = models.FloatField(name='Longitude Of GDT 1',
                                      unique=True, max_length=255, blank=False,
                                      help_text="Enter the location's Longitude, second when extracting from Google "
                                                "Maps.",
                                      default=1)

    latitude_uav = models.FloatField(name='Latitude Of UAV',
                                     unique=True, max_length=255, blank=False,
                                     help_text="Enter the location's Longitude, second when extracting from Google "
                                               "Maps.",
                                     default=1)
    longitude_uav = models.FloatField(name='Longitude Of UAV',
                                      unique=True, max_length=255, blank=False,
                                      help_text="Enter the location's Longitude, second when extracting from Google "
                                                "Maps.",
                                      default=1)

它是序列化程序:


from rest_framework import serializers
from .models import PostGDT1AndUAV


class PostGDT1AndUAVSerializer(serializers.ModelSerializer):
    class Meta:
        model = PostGDT1AndUAV
        fields = ('latitude_gdt', 'longitude_gdt', 'latitude_uav', 'longitude_uav')

尝试在 django shell 中打印对象的实例时,出现以下错误:


django.core.exceptions.ImproperlyConfigured: Field name `latitude_gdt` is not valid for model `PostGDT1AndUAV`.

另外,我正在尝试使模型中的字段更窄,也就是说,使用一个变量,

如果我要使用常规的 python 输入,我会做这样的事情:


        gdt1_coord = input("Enter the first GDT's Lat/Lon coordinates")

        lat1, lon1 = gdt1_coord.split(',')

        lat1 = float(lat1)
        lon1 = float(lon1)

        gdt1 = [lat1, lon1]

标签: pythonserializationdjango-rest-framework

解决方案


kwargname是数据库中字段的名称,因此不能包含任何空格。尝试将其替换为verbose_name


推荐阅读