django - Generate an unique identifier for a Model -
i have model containing filefield. i'd filefield have unique path.
at first, @ though using id of entry, django move file it's upload_to path before saving entry, id empty.
moreover, can't use title or other elements of model (except creation date) since can changed user. , prefer not copy/delete file every time user change title of it's entry (if use title part of path).
here start research, found these :
generate unique key , compare database. while key exist, generate new 1 (django, unique field generation) : problem potentials hits while database before having unique key
getting timestamp creation date. problem here, if 2 people add file @ exact same time, generate conflicts
i'd have unique id small possible, max length of 7 great. perfect solution have been have id of entry. know workaround (calling save() before moving files upload_to folder?) or if not, implementation best, based on 1 of solutions or 1 think better?
since filefield is, default, null=true, blank=true, possibility save model twice, first removing file value (=none), saving, , then, adding the file value (that stored in temporary var), , save again.
here code
# method goes in model def save(self, *args, **kwargs): # ignoring double save if update or if there no files if self.pk or not self.file: return super(mymodel, self).save(*args, **kwargs) old_file = self.file._file self.file = none super(mymodel, self).save(*args, **kwargs) self.file = old_file return super(mymodel, self).save(*args, **kwargs)
well, of course, result in double request database when create new entry, other solution come required @ least 1 hit database (key based unique constraint, key based on creation date, etc).
hope helps!
Comments
Post a Comment