开发者

Using functions in models to dynamically fill fields on object creation in Django

开发者 https://www.devze.com 2022-12-29 02:57 出处:网络
Within Django, can a function local to a model be called on object creation to dynamically fill a field?

Within Django, can a function local to a model be called on object creation to dynamically fill a field?

class someModel(models.Model):
    id = models.FloatField(primary_key=True, default=generate_id())

    def generate_id(self):
        newId=time.time()
        return newId

So far I haven't had any luck with getting it to work or with locatin开发者_运维技巧g documentation that covers it.


from django.db import models
import time

class SomeModel(models.Model):
    id = models.FloatField(primary_key=True)

    def save(self, *args, **kwargs):
       if not self.id:
           self.id = self.generete_id()
       super(SomeModel, self).save(*args, **kwargs)

    def generate_id(self):
       return time.time()

Also be warned that there may be some code in Django internals that relies on the fact that unsaved model instance has no primary key (at least it was the case in v1.0).

Another pitfall is generating id by calling time.time(). Chanses are that you'll get duplicate ids under heavy load. I'd suggest using uuid module to generate unique identifiers.


Yeah, this can be done using the signals framework.

from django.db import models
from django.core.signals import post_init

class SomeModel(models.Model):
    pass # *snip*

def generate_id(sender, **kwargs):
    kwargs.get('instance').newId = time.time()
        # ...

post_init.connect(SomeModel.generate_id)
0

精彩评论

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