在另一个Django模型字段中重用主键

2024-09-30 16:20:44 发布

您现在位置:Python中文网/ 问答频道 /正文

是否可以在Django模型的另一个字段中引用主键

例如,假设我想要一个看起来像BUG0001的字段,对应于带有pk=1的条目。实现这一目标的最佳方式是什么

我认为最好将主键保持为整数,因为这样更容易处理,而且我猜每次格式化主键都不是很有效


Tags: django模型目标方式条目整数pk主键
2条回答

是的,这是可能的,也很容易做到。就这么做吧

先做主键 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 string formatting

另一种方法是使用@property{a2}或@cached_property{a3}

在您的情况下,@cached_属性可能更好propertycached_property将不会保存在数据库中。但您可以在模板中调用它,就好像这是另一个模型字段一样

使用属性和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)

相关问题 更多 >