Reputation: 553
Is it possible to reference the primary key in another field in a Django model?
For example, let's say I want to have a field looking like BUG0001
corresponding to the entry with pk=1
. What is the best way to achieve this?
I think it is best to keep the primary key as an integer as it is easier to deal with, and I guess formatting the primary key every time is not very effective.
Upvotes: 0
Views: 736
Reputation: 3248
Yes you can.
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)
You can check out python string formatting.
Another way is to use @property
docor @cached_property
doc .
In your case, @cached_property may be better. property
and cached_property
will not be saved in database. but you can call it in your template as if this is another model field.
Obvious benefit of using property and cahced_property is that you will not need to save to db every time you need to save model.
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)
Upvotes: 0
Reputation: 359
Yes it possible and easy to do. Just do this
First make primary key
from django.db import models class Fruit(models.Model): name = models.CharField(max_length=100,primary_key=True)
And then call it where you want as foreign key
foreign= models.ForeignKey(Reporter, on_delete=models.CASCADE)
Upvotes: 1