I'm new to Django. I want to make an API that automatically generate a value to a field when POST to this api with Django.
def gen_code(k):
return # a value
class generate_code(models.Model):
code = models.CharField(max_length=100, default="", unique=True)
generated_code = gen_code(code value) #generated with the value in code field
Something like the code above. How can I make that
You cannot do this in the declaration of the fields, as there is no "instance" at that point in time. You can override the default save() method to accomplish this:
class GeneratedCode(models.Model):
code = models.CharField(max_length=100, default="", unique=True)
generated_code = models.CharField(max_length=100, null=True)
def save(self, *args, **kwargs):
if not self.generated_code:
self.generated_code = gen_code(self.code)
super().save(*args, **kwargs)
This isn't perfect, but it should get you started. This code assumes that you always want to create a generated_code if it doesn't already exist, and you always want to generate it based on the current instance's "code" field.
It's also not a great idea to have a "default" value combined with unique=True. This will open you up to Unique constraint errors rather than having django complain that the field is mandatory - which it handles gracefully.