我有以下模型,其中一个字段基于其他字段(类似于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
我想在覆盖save方法后将 code_combined 字段的primary_key设置为True,这样我就可以在其他模型上将其用作外键。有没有办法做到这一点?
答案 0 :(得分:2)
为什么不告诉Django你使用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',)
为什么不将code_combined
字段设为唯一,并将其作为to_field
在ForeignKey中引用?
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')
...
在这里谨防Unicode;除非您使用的是Python 3!