首页 > 解决方案 > Python,Django rest框架,创建一个包含选项或自由文本的字段

问题描述

我有一个 Django 休息框架 API。

我希望向其中添加一个字段,其中包含选项或自由文本。

我希望如果用户决定向该字段添加一个新值,它将被添加到数据库中。

我有以下现有模型:

class Points(models.Model):
    mission_name = models.CharField(name='MissionName',
                                    verbose_name="Mission Name",
                                    unique=True,
                                    max_length=255,
                                    blank=False,
                                    help_text="Enter the mission's name"
                                    )

        location_name = models.CharField(choices= # fetch known locations from the DB 
                                                  #or create a new one) 
                                     # Show existing options or input a new one.
                                     # If an existing location has been chosen then it's Latitude and Longitude are of the fetched object.
                                     # Pretty sure that this kind of action belongs in the serializer or the view.



    latitude = models.FloatField(name="GDT1Latitude",
                                 verbose_name="GDT 1 Latitude",
                                 unique=False, max_length=255, blank=False,
                                 help_text="Enter the location's Latitude, first when extracting from Google Maps.",
                                 default=DEFAULT_VALUE)
    longitude = models.FloatField(name="GDT1Longitude",
                                  verbose_name="GDT 1 Longitude",
                                  unique=False, max_length=255, blank=False,
                                  help_text="Enter the location's Longitude, second when extracting from Google Maps.",
                                  default=DEFAULT_VALUE)

    area = models.CharField(
        name='Area',
        max_length=8,
        choices=AREAS,
    )

标签: pythondjangodjango-rest-framework

解决方案


您应该制作另一个模型位置,并将外键放入您的点模型中:

enter code here
class Points(models.Model): 
location_name = models.ForeignKey(Location,on_delete=models.SET_NULL,null=true)


class Location(models.Model):
#any info you want to store

推荐阅读