LD8
LD8

Reputation: 306

Django - models - access a value of a field within a class

class Tag(models.Model):
    '''Items have tag will have according discount percentage'''

    tag_discount_percentage = models.IntegerField()

    slogan_default = 'Purchase NOW for extra {}% off!'.format(tag_discount_percentage.get_prep_value(value))

    slogan = models.CharField(max_length=200, default=slogan_default)

    def __str__(self):
        return self.slogan

This code raised exception:

slogan_default = 'Purchase NOW for the extra {}% off!'.format(tag_discount_percentage.get_prep_value(value)) NameError: name 'value' is not defined

urggg!

Question 1: How does one access a field's own value within that class? Or is there a better way to set the default of a CharField?

tag_discount_percentage itself is <django.db.models.fields.IntegerField> but I want the value


Question 2: Could I set a digit limitation to an IntegerField? all I found was max_length which prompts a warning saying that 'max_length will be ignored'...

Upvotes: 0

Views: 251

Answers (2)

Charnel
Charnel

Reputation: 4432

Answering your second question - it's not obvious what you mean by "digit limitation". If you are interested in preventing the value from being out of defined ranges, then you can use validators:

from django.core.validators import MaxValueValidator, MinValueValidator

class Tag(models.Model):
    '''Items have tag will have according discount percentage'''
    tag_discount_percentage = models.IntegerField(default=0, validators=[MinValueValidator(1), MaxValueValidator(100)])

Else, if you meant to limit decimal places, then you should use a decimal field instead of integer.

Also, commenting on your first question - you simply can't set the default related with value of another field because on the moment when instance(record) is saved, field values isn't set up yet. default agrument can be a callable, but without any reference to an objects it's being used for. You may consider using pre_save signal instead to set a field value "by default" depending on another fields.

Upvotes: 1

LD8
LD8

Reputation: 306

Attempt to answer Question 1:

I'm not sure if this is the best answer but it solved the problem. It seems that it's not possible (or I simply do not know how) to access the value of a field within the class so I figured something else:

class Tag(models.Model):
    '''Items have tag will have according discount percentage'''
    tag_discount_percentage = models.IntegerField(default=0)
    slogan = models.CharField(max_length=200, blank=True)

    def __str__(self):
        return self.slogan if self.slogan else self.slogan_default

    @property
    def slogan_default(self):
        return 'Purchase NOW for the extra {}% off!'.format(self.tag_discount_percentage)

Erm.. I'd really appreciate if anyone could answer Question 2. Cheers~

Upvotes: 0

Related Questions