[Answered ]-Django Custom Manager add attribute

2👍

If you need nonDbField’s value to be related to the field1 (or any other field in the model) you can try something like this:

Class MyModel(models.Model):

    # your fields here...

    def _nonDbField(self):
        return SomeObject.objects.get(pk=self.field1)
    nonDbField = property(_nonDbField)

This allows you to do something like this:

MyModel.objects.get(pk=1).nonDbField

Keep in mind that you are making a database query each time you access nonDbField (which may or may not be detrimental to your DB performance).

0👍

you can use property for your calculated fields

Class MyModel(models.Model):

# your fields here...
first_name = models.CharField()
last_name = models.CharField()

@property
def fullname(self):
    return f"{self.first_name} {self.last_name}"

This allows you to do something like this:

obj = MyModel.objects.get(pk=1)
print(obj.fullname)

Leave a comment