python - How to pre-populate field from ForeignKey on Django via decorator? -
suppose have 3 classes on model in django 1.11 & python3.5:
class 1:
class country(models.model):     name = models.charfield(max_length=255)      def __str__(self):         return self.name   class 2:
class city(models.model):     country = models.foreignkey(country)     name = models.charfield(max_length=255)     latitude = models.decimalfield(max_digits=15, decimal_places=10)     longitude = models.decimalfield(max_digits=15, decimal_places=10)      def __str__(self):         return self.name   class 3:
class profile(abstractuser):     username = models.foreignkey(user, max_length=100, blank=false, unique=true)     address = models.charfield(max_length=255, blank=false)     city = models.foreignkey(city, on_delete=models.cascade, related_name="city_set", max_length=100, blank=false, null=true)     country = models.charfield(max_length=255, blank=false)     birthplace = models.foreignkey(city, on_delete=models.cascade, related_name="birthplace_set", max_length=100, blank=false, null=true)     latitude = models.decimalfield(max_digits=15, decimal_places=10)     longitude = models.decimalfield(max_digits=15, decimal_places=10)          def __str__(self):         return self.username      @property     def country(self):         if not self.city:             return false         else:             negara = city.objects.get(name=self)             return negara.country      @property     def latitude(self):         if not self.birthplace:             return false         else:             lat = city.objects.get(latitude=self)             return lat.latitude      @property     def longitude(self):         if not self.birthplace:             return false         else:             lnt = city.objects.get(longitude=self)             return lnt.longitude   my questions are:
- how , autofill/pre-populate country's attribute @ profile's class city's attribute (which's foreignkey city's class)? i've tried using @property decorator nothing value.
 - can use same class (from city's class) foreignkey fields in 1 class (to profile's class) twice? in case city & birthplace attribute, , repeat question above latitude & longitude's attribute birthplace's attribute.
 
what purpose of populating these fields , @property calls? rather use direct call this:
    person.city.country.name     person.city.longitude     person.city.latitude   it works longitude , latitude properties well. if need pre-populated charfield can in save() method so:
    class person(models.model):     ...     def save(self, *args, **kwargs):       self.country = self.city.country.name       self.longitude = self.city.country.name       self.latitude = self.city.country.name       super(person, self).save(*args, **kwargs)   and yes, can use many foreignkey fields want.
Comments
Post a Comment