Reputation: 2197
I have a following model:
class BoatImage(models.Model):
boat_photo = models.ImageField(upload_to=get_timestamp_path, blank=True,
verbose_name='Boat photo', )
boat = models.ForeignKey("BoatModel", on_delete=models.SET_NULL, verbose_name="Boat ForeignKey", null=True)
memory = models.PositiveSmallIntegerField(blank=True, null=True, default = ???)
goal is to when entry is made, default in “memory” field should pick up “boat’ field ID or PK and save it the memory “field”, that is, id in both fields should coincide. I am trying to use default with method like:
def funk(self):
return self.boat.id # or self.boat.pk or self.boat_id – no difference
But it says – funk should return int, not foreignkey(error)
Question is how to store foreignkey id of the “boat” field in “memory” field when entry is created???
It is possible to do it in save() method but it is quite non-elegant solution in my opinion.
Thanks...
implementation via save()
def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
if self.boat and not self.memory: # save
self.memory = self.boat_id
elif not self.boat and self.memory: # restore
self.boat_id = self.memory
elif self.boat and self.memory and self.boat_id != self.memory: # correct
self.memory = self.boat_id
models.Model.save(self, force_insert=False, force_update=False, using=None,
update_fields=None)
Upvotes: 0
Views: 39
Reputation: 1026
As per my unserstanding, you can do one thing first save the model with
default=0
for the memory
field then to assign the id run an update query
Upvotes: 1