[英]Reuse Primary Key in another Django model field
是否可以在 Django model 的另一个字段中引用主键?
例如,假设我想要一个看起来像BUG0001
的字段,对应于pk=1
的条目。 实现这一目标的最佳方法是什么?
我认为最好将主键保留为 integer 因为它更容易处理,而且我猜每次都格式化主键不是很有效。
是的,这可能而且很容易做到。 就这样做
首先from django.db import models class Fruit(models.Model): name = models.CharField(max_length=100,primary_key=True)
然后在你想要的地方调用它作为外键foreign= models.ForeignKey(Reporter, on_delete=models.CASCADE)
是的你可以。
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)
您可以查看python 字符串格式。
另一种方法是使用@property
doc或@cached_property
doc 。
在您的情况下,@cached_property 可能会更好。 property
和cached_property
不会保存在数据库中。 但您可以在模板中调用它,就好像这是另一个 model 字段一样。
使用 property 和 cahced_property 的明显好处是每次需要保存 model 时都不需要保存到 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.