简体   繁体   中英

django custom field - how to modify another field's value

i am developing a django custom field . Inside the custom field def, how can i write some code that saves another field ? For example, inside the def of custom field, I have written pre_save method but after assigning values to other model fields, I have called model_instance.save() method but that resulted in an infinite loop. Can you tell me how to do this ?

class FullNameField(models.CharField):

    def contribute_to_class(self, cls, name):  
        firstname_field = models.CharField(
                null=True, blank=True, max_length=50)
        lastname_field = models.CharField(
                null=True, blank=True, max_length=50)

        firstname_field.creation_counter = self.creation_counter  
        lastname_field.creation_counter = self.creation_counter  

        cls.add_to_class('firstname', firstname_field )  
        cls.add_to_class('lastname', lastname_field )  

        super(FullNameField, self).contribute_to_class(cls, name) 

The above code successfully creates the new fields firstname and lastname during syncdb, wha ti want to do is, when i populate the fullnamefield, firstname and lastname should also be populated. This fullname logic is just an example, but the requirement is same.

You can use the pre_save signal to get notified when the class is saved.

Add this to your contribute_to_class method:

from django.db.models.signals import pre_save

def populate_fullname(sender, instance, raw, **kwargs):
    if raw:
        return # be nice to syncdb
    fullname = u'%s %s' %  (instance.firstname, instance.lastname))
    setattr(instance, name, fullname)

pre_save.connect(populate_fullname, cls)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM