Django Model Field Default Based Off Another Field in Same Model

Django Model Field Default Based Off Another Field in Same Model

Models certainly do have a "self"! It's just that you're trying to define an attribute of a model class as being dependent upon a model instance; that's not possible, as the instance does not (and cannot) exist before your define the class and its attributes.

To get the effect you want, override the save() method of the model class. Make any changes you want to the instance necessary, then call the superclass's method to do the actual saving. Here's a quick example.

def save(self, *args, **kwargs):
if not self.subject_init:
self.subject_init = self.subject_initials()
super(Subject, self).save(*args, **kwargs)

This is covered in Overriding Model Methods in the documentation.

Setting Djando field default value based on another field

Similar answered question. I am attaching the official documentation as well as the link to the answered question.

Models certainly do have a "self"! It's just that you're trying to define an attribute of a model class as being dependent upon a model instance; that's not possible, as the instance does not (and cannot) exist before your define the class and its attributes.

To get the effect you want, override the save() method of the model class. Make any changes you want to the instance necessary, then call the superclass's method to do the actual saving. Here's a quick example.

def save(self, *args, **kwargs):
if not self.subject_init:
self.subject_init = self.subject_initials()
super(Subject, self).save(*args, **kwargs)

Model Overriding Documentation

Django Model Field Default Based Off Another Field

Django models: Set default relative to another field

You cannot assign a default value on a field dependent on another before having a model instance. To achieve the same you can override the save() method of the model:

class SomeModel(models.Model):

...

def save(self, *args, **kwargs):
self.second_visit = self.first_visit + datetime.timedelta(weeks=3)
super().save(*args, **kwargs)

Django model field with default value from another model

Do you want the default value of fo2 to equal to something related with the specific instance of aaa at creation?

The way to do that would be to override the save method

class ModelB(models.Model):
aaa = models.ForeignKey(ModelA)
tar = models.Char(Field(max_length=255, default="")
fo2 = models.CharField(max_length=255)

def save(self, *args, **kwargs):
if self.fo2 is None:
self.fo2 = self.aaa._value_taken_from_Model_A
super(ModelB, self).save(*args, **kwargs)

How can I define a django model's field default value to be another field value?

Overwrite save method on model.

def save(self, force_insert=False, force_update=False, using=None,  update_fields=None):  
if self._state.adding:
self.max_bid = self.start_bid
super().save(force_insert, force_update, using, update_fields)

Model field based on other fields?

Yes, the best way to handle this would be to override the save method of the model

class Foo(models.Model):
x = models.PositiveSmallIntegerField()
y = models.PositiveSmallIntegerField()
z = models.PositiveSmallIntegerField()

score = models.PositiveSmallIntegerField()

def save(self, *args, **kwargs):
self.score = self.x + self.y + self.z
super(Foo, self).save(*args, **kwargs) # Call the "real" save() method.

Make sure you take care of the necessary validations.

More on this here: official documentation

Django Add default value to model field having the value of another field

You should preform this step by overriding the save method. You can also create a function that updates all the past models.

models.py

class ModelB(models.Model):
id = models.IntegerField()
index = models.IntegerField(null=True)
def save(self, *args, **kwargs):
if not self.index:
self.index = self.id
super().save(*args, **kwargs)

To create a 'refresh' function, try this:

admin.py

...
from .models import ModelB

def refresh_objects(modeladmin, request, queryset):
for object in queryset:
object.save()

refresh_objects.short_description = "Update selected objects."

class ModelBAdmin(admin.ModelAdmin):
actions = [refresh_objects]

admin.site.register(ModelB, ModelBAdmin)

Now, simply head to the admin site, select all the models to refresh, and run this action. (It can be found in the dropdown)

how to make a field unique based on another filed in django models?

On your Product table:

class Product(...):
...

class Meta:
unique_together = ('shop', 'name')

This will ensure Products must have a unique name across the Shop they are related to.



Related Topics



Leave a reply



Submit