Django如何添加自定义位置字段



在我的配置文件模型中,我想在自定义位置字段中保留countrycity, country值。此外,必须提供country值。因此,我制作了一个实现MultiValueField的LocationField。我在Django不是很高级,所以我怎么能只需要country呢?此外,我不确定这个代码是否完全正确。

p.S:我可以在Profile中制作城市和乡村字段,但将它们放在一个字段中似乎更整洁。

型号.py

from cities_light.models import City, Country
class Profile(models.Model):
user                = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')
first_name          = models.CharField(verbose_name='first name', max_length=10, null=False, blank=False, default='baris') 
last_name           = models.CharField(verbose_name='last name', max_length=10, null=False, blank=False, default='baris')
profile_photo       = models.ImageField(verbose_name='profile photo', ) #TODO add upload to
about               = models.CharField(verbose_name='about', max_length=255, null=True, blank=True)
spoken_languages    = models.CharField(verbose_name='spoken languages', max_length=255, null=True, blank=True)
location            = LocationField()

class LocationField(MultiValueField):

def __init__(self, **kwargs):
fields = (
Country(),
City()
)
super.__init__(fields=fields, require_all_fields=False, **kwargs)

也许您想要Location型号?您可以添加一个城市或国家的字段type,并添加一个unique_together字段以将配置文件限制为每个城市和国家:

COUNTRY = 0
CITY = 1
class Location(models.Model):
LOCATION_TYPE_CHOICES = ((COUNTRY, 'country'), (CITY, 'city'))
profile = models.ForeignKey('Profile', ..., related_name='locations')
name = models.CharField(...)
type = models.IntegerField(..., choices=LOCATION_TYPE_CHOICES)
class Meta:
unique_together = ('profile', 'type')

然后你可以访问配置文件的位置,如下所示:

from . import models
profile = models.Profile.objects.get(id="<pofile-id>")
# either a location instance of type 'country' or None if none exist:
country = profile.locations.filter(type=models.COUNTRY).first()
# either a location instance of type 'city' or None if none exist:
city = profile.locations.filter(type=models.CITY).first()

最新更新