Ryan Saxe
Ryan Saxe

Reputation: 17829

Django custom save not working

So I have the following model:

class Info(models.Model):
    user_id = models.BigIntegerField(primary_key=True)
    #...
    def save(self,*args,**kwargs):
        print 1
        is_created = False
        if not self.pk:
            print 2
            is_created = True
        super(Info, self).save(*args, **kwargs)
        print 3
        if is_created:
            print 4
            signals.info_created.send(sender=self.__class__,info=self)

now I have those print statements to keep track of what is going on.when I run either Info.create(...) or

info = Info(...)
info.save()

I get the following output:

1
3

which suggests that the if not self.pk statement evaluated to false. Now I assume this is because I have a custom primary key that needs to be given on the creation of that object. So here is my question: is my assumption correct? Regardless if it is or is not, how can I get this custom save to cooperate?

Upvotes: 0

Views: 137

Answers (1)

vadimchin
vadimchin

Reputation: 1497

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

Upvotes: 1

Related Questions