1

I have the following model in which one the fields is based on other fields (similar to this):

from django.db import models

class Model_Model01(models.Model):

    code_01 = models.CharField(max_length = 2, null = False, blank = False)
    code_02 = models.CharField(max_length = 3, null = False, blank = False)
    code_combined = models.CharField(max_length = 6, null = True, blank = False, primary_key = False)

    def save(self, *args, **kwargs):
        self.code_combined = "{}.{}".format(self.code_01, self.code_02)
        super(Model_Model01, self).save(*args, **kwargs)

    def __unicode__(self):
            return self.code_combined

I would like to set the primary_key of code_combined field as True after overriding the save method so I can use it as a foreignkey on other model. Is there a way to do this?

Fxs7576
  • 1,259
  • 4
  • 23
  • 31

1 Answers1

2

Why not tell Django that you are using a composite key for this model using unique_together?

Composite primary key in django

https://docs.djangoproject.com/en/2.0/ref/models/options/#unique-together

class Model_Model01(models.Model):

    code_01 = models.CharField(max_length = 2, null = False, blank = False)
    code_02 = models.CharField(max_length = 3, null = False, blank = False)
    class Meta:
        unique_together = ('code_01', 'code_02',)

Update

Why not have the code_combined field be Unique, and reference it in your ForeignKey as the to_field?

class Model_Model01(models.Model):

    code_01 = models.CharField(max_length = 2, null = False, blank = False)
    code_02 = models.CharField(max_length = 3, null = False, blank = False)
    code_combined = models.CharField(max_length = 6, unique = True)

    def save(self, *args, **kwargs):
        self.code_combined = "{}.{}".format(self.code_01, self.code_02)
        super(Model_Model01, self).save(*args, **kwargs)

    def __unicode__(self):
            return self.code_combined


class Model_Model02(models.Model):
    model_1 = models.ForeignKey(Model_Model01, to_field='code_combined')
    ...

Beware of Unicode here; unless you are using Python 3!

rtindru
  • 5,107
  • 9
  • 41
  • 59