> I have overriden the save method on my model, and want to use the id
> field (default autoincrementing pk) to set one of the other fields.
>
> Is this ok:
>
>   class MyModel(models.Model):
>     ...
>     def save(self, *args, **kwargs):
>       super(MyModel, self).save(*args, **kwargs)
>       self.some_string_field = "Some text with id=%d" % self.id
>       super(MyModel, self).save(*args, **kwargs)
>
> It seems to work, but I'm confused about some side effects.  If I use
>   obj, created = MyModel.get_or_create(...)
> then created is always False, even when a new object is created.  Is
> that because of the 2 super.save() calls?

That seems a reasonable assumption, though I haven't looked at the
get_or_create() code.

When I've needed to do something similar (like using the pk of a model
as a folder name for file uploads, to keep different objects'
filenames from colliding) I've opted instead for creating a surrogate
key (in that example, a uuid).

Can you tell me a bit more about your use case? Obviously it must be
something a little more complex than simply storing a string that
contains the pk, or you would just have a method to calculate that
string. What exactly is it that requires access to the pk on create?

Regards
Scott

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.

Reply via email to