Python 在另一个Django模型字段中重用主键
是否可以在Django模型的另一个字段中引用主键 例如,假设我想要一个类似于Python 在另一个Django模型字段中重用主键,python,django,Python,Django,是否可以在Django模型的另一个字段中引用主键 例如,假设我想要一个类似于BUG0001的字段,对应于pk=1的条目。实现这一目标的最佳方式是什么 我认为最好将主键保持为整数,因为这样更容易处理,而且我想每次格式化主键都不是很有效。可以 class Product(models.Model): other= models.CharField(max_length=50, blank=True, null=True) def save(self, *args, **kwar
BUG0001
的字段,对应于pk=1
的条目。实现这一目标的最佳方式是什么
我认为最好将主键保持为整数,因为这样更容易处理,而且我想每次格式化主键都不是很有效。可以
class Product(models.Model):
other= models.CharField(max_length=50, blank=True, null=True)
def save(self, *args, **kwargs):
self.another = "BUG%d" %(self.pk)
super(Product, self).save(*args, **kwargs)
你可以退房
另一种方法是使用@property
或@cached\u property
在您的情况下,@cached_属性可能更好<代码>属性和缓存的_属性
将不会保存在数据库中。但您可以在模板中调用它,就好像这是另一个模型字段一样
使用属性和cahced_属性的明显好处是,您不需要每次需要保存模型时都保存到db
from django.utils.functional import cached_property
class Product(models.Model):
# since we want to have "another" as a property, you do not need to
# generate a field called "another"
#another= models.CharField(max_length=50, blank=True, null=True)
somefield = models.CharField(max_length=50, blank=True, null=True)
@cached_property
def another(self):
return "BUG%d" %(self.pk)
# not sure why the above string formatting not working for you.
# you can simply do:
return "BUG" + str(self.pk)
def save(self, *args, **kwargs):
super(Product, self).save(*args, **kwargs)
是的,这是可能的,也很容易做到。就这么做吧 先做主键
来自django.db导入模型类水果(models.Model):name=models.CharField(max_length=100,primary_key=True)
然后在需要的地方将其称为外键
foreign=models.ForeignKey(Reporter,on_delete=models.CASCADE)
我的答案或Vishal的答案对您有效吗?不幸的是,我仍在寻找解决方案(目前我只是在查询结果后格式化字符串…)当我保存一个产品条目时,另一个字段被None替换:BUG/None
oops!我的错。由于pk
是整数,我应该使用%d
而不是%s
。请查看更新的答案。感谢您的更正,但pk仍然没有。经过一些研究,似乎pk在创建条目之前无法被引用。我已经在我的项目中对此进行了测试,没有问题。它显示Bug1您可以显示您的模型吗。py?我宁愿在主键字段中保留一个自动递增的整数。