简体   繁体   English

如何访问Django模型的实例化属性

[英]How to access instantiated attribute of django model

models.py 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 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. 在这里,我试图创建一个alpha_id模型属性,该属性基于自动创建的整数id属性建立一个字母数字id。 I wrote a function that performs the algorithm, and I just need to send that method the id of the current instantiated model. 我编写了一个执行算法的函数,只需要向该方法发送当前实例化模型的ID。 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. 我需要做的就是弄清楚如何将我的Sample模型的当前实例的id属性传递给该函数。

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. 显然,我的问题是我没有引用类Sample的实例化,因此使用“ self.id”会导致错误。 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. 我觉得解决方案涉及到定义__init__方法的事情,但是我不太确定如何去做。 I have looked at the Model.py base class and I couldn't quite find where the id attribute is defined. 我查看了Model.py基类,但找不到完全定义id属性的位置。

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? 综上所述,如何访问实例化django模型的当前ID,以便可以使用该整数值来通知另一个属性的创建?

Instead of making alpha_id a class attribute, you need to make it an instance attribute using the @property decorator on an instance method: 无需将alpha_id为类属性,而需要使用实例方法上的@property装饰器将其设置为实例属性:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM