BartoNaz
BartoNaz

Reputation: 2893

Set model field of child class as primary_key in Django

I have an abstract model class:

class AbstractClass(models.Model):
    filename_base = models.CharField(max_length=25, blank=True, null=True)

    class Meta:
        abstract = True

Is it possible to make a child class with primary_key set to this field without rewriting the field definition itself? I've tried the class definition below,

class ChildClass(AbstractClass):
    filename_base.primary_key = True

but it raises NameError: name 'filename_base' is not defined

Upvotes: 0

Views: 91

Answers (1)

MicroPyramid
MicroPyramid

Reputation: 1630

I hope this helps.

class ChildClass(AbstractClass):
    pass
ChildClass._meta.get_field('filename_base').blank = False
ChildClass._meta.get_field('filename_base').null = False
ChildClass._meta.get_field('filename_base').primary_key = True

And Primary key should be blank=False and null=False.

Note: in AbstractClass id already has primary key my answer is for NameError.

Upvotes: 1

Related Questions