David Dahan
David Dahan

Reputation: 11162

Django: Auto Instantiation of custom primary key?

I have a class with a custom pk field, and a classmethod to generate this special pk:

class Card(models.Model):
    custom_pk = models.BigIntegerField(primary_key=True)
    other_attr = ...

    @classmethod
    def gen_id(cls):
        # ...
        return the_id

Now, I suppose I can create object (in a view for example) doing this:

Card.objects.create(custom_pk=Card.gen_id(), other_attr="foo")

But I'd like to have the same result using the classic way to do it:

Card.objects.create(other_attr="foo")

Thanks!

Upvotes: 1

Views: 88

Answers (1)

pajton
pajton

Reputation: 16226

You can use pre_save signal to supply your primary key is missing. This signal handler will be called before each call to Card.save() method, therefore we need to make sure that we won't override custom_pk if already set:

@receiver(pre_save, sender=Card)
def add_auto_pk(sender, instance, **kwargs):
    if not instance.custom_pk:
        instance.custom_pk = Card.get_id()

See Django signal documentation for more details.

Upvotes: 3

Related Questions