开发者

Django Models Manager for saving custom processed data in a field

开发者 https://www.devze.com 2023-02-07 20:29 出处:网络
A noob here. I have a model class where I want to save something processed in one of the fields of that table.am trying to use a ModelManager for that but do not know if it is possible or how to.

A noob here. I have a model class where I want to save something processed in one of the fields of that table. am trying to use a ModelManager for that but do not know if it is possible or how to.

I want to save a custom url for each post here. So I want to have a method in PostManager class which will calculate hash of something (say current time) and save it as a url. I could not find any syntax help so asking it here.

class Post (models.Model):
    name = models.CharField(max_length=1000, help_text="required, name of the post")
    description = models.TextField(blank=True)
    created_datetime = models.DateTimeField(auto_now_add=True, editable=False)
    modified_datetime = models.DateTimeField(auto_now=True, editable=False)
    custom_hashed_url = models.CharField(unique=True, max_length=1000, editable=False)

def save(self, *args, **kwargs):
        #How to refer to the custom_hashed_url in the Post class?开发者_Go百科
        super(Model, self).save()


If you want the url to be saved in the database with the rest of the information, it will need to appear in the model as a field.

Change the url to an appropriate field type and set its 'editable' attribute to False, as you've done with the datetime fields. This will stop it appearing in forms.

You could then override the model's save method (see Django docs) so that it calculates the post's url and adds it automatically as the instance is saved!

Model managers are used for 'model level' interactions that work with many instances, or sets of instances. In this case you are trying to manipulate a single instance. We use a field to store the information in the database for the record and a method (in this case overriding a built-in method to hook into the default behaviours) to calculate the field's value.

Good luck!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号