How to access instantiated attribute of django model

时间:2015-09-01 22:02:42

标签: python django django-models

models.py

from django.db import models

from alpha_id import get_alpha_id


class Sample(models.Model):
    alpha_id = get_alpha_id(self.id)
    sample_name = models.CharField(max_length=30)
    entry_date = models.DateField(auto_now_add=True)


    def __unicode__(self):
        return self.alpha_id

alpha_id.py

import string

ALL_LETTERS = string.ascii_uppercase.replace('F', '').replace('I', '').replace('L', '').replace('O', '').replace('V', '')

def get_alpha_id(id):
    """ Return the alpha numeric ID according to the current 
        integer id.
    """
    global ALL_LETTERS
    alpha =  ALL_LETTERS[(id%len(ALL_LETTERS))-1]
    return str(id) + '_' + alpha

Here, I am trying to create a alpha_id model attribute which establishes an alpha numeric id based on the automatically created integer id attribute. I wrote a function that performs the algorithm, and I just need to send that method the id of the current instantiated model. For example:

>>> get_alpha_id(1)
1_A
>>>get_alpha_id(2)
2_B

Anyways I have that logic all figured out. All i need to do is figure out how to pass to that function the id attribute of the current instantiation of my Sample model.

Obviously my problem here is that I am not referring to an instantiation of the class Sample, so the use of "self.id" is causing an error. To be specific:

alpha_id = get_alpha_id(self.id)
NameError: name 'self' is not defined

I have a feeling the solution involves something to do with defining an __init__method but I am not quite sure how I would go about doing it. I have looked at the Model.py base class and I couldn't quite find where the id attribute is defined.

To sum it up, how can I access the current id of an instantiated django model so that I can use that integer value to inform the creation of another attribute?

1 个答案:

答案 0 :(得分:3)

Instead of making alpha_id a class attribute, you need to make it an instance attribute using the @property decorator on an instance method:

class Sample(models.Model):
    sample_name = models.CharField(max_length=30)
    entry_date = models.DateField(auto_now_add=True)

    @property
    def alpha_id(self):
        return get_alpha_id(self.id)

    def __unicode__(self):
        return self.alpha_id