How to prepopulate ID in Django
I have simple question model :
class Question(Polymorph):
text = models.CharField(max_length=256)
poll = models.ForeignKey(Poll)
index = models.IntegerField()
And I would like to prepopulate ( when saving ) index field with ID value. Of course before save I dont have ID value ( its created after it ), so I wonder what is the simplest way to do it ? Any ideas ?
I think about django-signal, but then I will have to call 开发者_如何学JAVAsave() method twice.
However you do it, you'll have to call save twice. The ID is generated directly by the database server (except for sqlite, I believe) when the new row is INSERTed, so you'll need to do that in any case.
I would ask if you really need to have the ID value in your index
field, though. It's always available as obj.id
, after all, so even if you want it as part of a longer value you can always calculate that dynamically via a property.
Yes, trying to figure the next ID out from somewhere wouldn't be portable. Even simpler than using signals is putting something like this in your save method:
def save(self, *args, **kwargs):
"""Save method for Question model"""
if not self.id:
super(Question, self).save(*args, **kwargs)
# Fill the index field
self.index = self.id # plus whatever else you need
return super(Question, self).save(*args, **kwargs)
I guess you'll have to go this way if you can't fully derive the id of the object from the string you get as the input to the filter. But if your string where "something-{id}-something-else" it would be better to get rid of the index field and extract the id value from the string using a regexp and then filter directly by the id with Questions.objects.filter(id=id)
One way to circumvent the double commit is to use something besides an autoincrementing primary key. Django doesn't really care what the primary key is so long as there is one, just one, and it is either a string or an integer. You could use something like a guid, which you can generate on the fly in your models at the time they are initialized, or you can let the database set it for you when you don't care what it is (assuming your database supports guids).
精彩评论