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)
是的,这是可能的,也很容易做到。就这么做吧
先做主键
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)
是的,你可以
你可以签出python string formatting
另一种方法是使用
@property
{a2}或@cached_property
{a3}在您的情况下,@cached_属性可能更好
property
和cached_property
将不会保存在数据库中。但您可以在模板中调用它,就好像这是另一个模型字段一样使用属性和cahced_属性的明显好处是,您不需要每次需要保存模型时都保存到db
相关问题 更多 >
编程相关推荐