[Answer]-Django custom save not working

1πŸ‘

βœ…

in base.py Model:

def _get_pk_val(self, meta=None):
    if not meta:
        meta = self._meta
    return getattr(self, meta.pk.attname)

meta.pk point on user_id, meta filled from kwargs in constructor before calling create or save

class Info(models.Model):
    user_id = models.BigIntegerField(primary_key=True)
    text = models.TextField()

    def save(self,*args,**kwargs):
        print 1
        is_created = False
        if not self.pk:
            print 2
            is_created = True

        self.pk = 20 #set pk before super call to pass validation

        super(Info, self).save(*args, **kwargs)
        print 3
        if is_created:
            print 4


Info.objects.create(text='wew')
#prints 1 2 3 4
πŸ‘€vadimchin

Leave a comment