Django model fields: default self reference

I am having trouble understanding this, and come up with a way to link to self inside the default keyword of the model field:

Here is what I have:

 class Bank(models.Model): number = models.CharField(max_length=10) class Account(models.Model): bank = models.ForeignKey(Bank, related_name="accounts") number = models.CharField(max_length=20) created = models.DateTimeField(auto_now_add=True) creator = models.ForeignKey(User) # This is the guy special_code = models.CharField(max_length=30, default='%s-%s' % (self.number, self.bank.number)) 

So, I'm trying to access myself inside the class definition, which does not seem to work because python does not know where I am, since it is not an object yet.

I tried different things like:

 special_code = models.CharField(max_length=30, default='%s-%s' % (number, bank.number)) 

But in this case, it does not recognize bank.number , because the bank has only a property with models.ForeignKey .

I also tried using the method inside the Account class:

 def bank_number(self): return self.bank.number 

and then:

 special_code = models.CharField(max_length=30, default='%s-%s' % (number, bank_number())) 

It was a little stupid because it still needs itself. Is there a way I can do this?

I need it to store the number inside the database, so using this method will not help:

 def special_number(self): return '%s-%s' % (self.number, self.bank.number) 
+4
source share
3 answers

I don’t think there is any way to access myself by default. There are several other approaches for setting a field value:

If you do not want the user to be able to change the value, override the model saving method and set it there.

If the default is just a sentence, and you want to allow the user to change it, then override the __init__ form method, then you can access self.instance and change the value of the original field value.

+4
source

Instead of specifying a default value for the field, you probably want to override the save() method and populate the field just before saving the object to the database. The save() method also has access to self . Here is an example in the docs for this:

https://docs.djangoproject.com/en/dev/topics/db/models/#overriding-model-methods

+2
source

As already mentioned, override the save() method of your model to set the value to special_code . The default field option should not depend on other model fields, so this will not work.

Also, look at the editable parameter if you do not want the field to be edited.

 special_code = models.CharField(max_length=30, editable=False) 

Prevents field rendering in ModelForms that you created from the model.

+2
source

Source: https://habr.com/ru/post/1446080/


All Articles