如何在django动作中获取模型字段的值?

时间:2016-05-19 22:00:39

标签: django python-3.x

我正在尝试在我的管理应用中执行操作,在此操作中,我必须检索模型应用中的字段值。但我没有成功。

我的模特应用:

class Entrada(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
    medicamento = models.ForeignKey(Medicamento, verbose_name=_(u'Medicamento'))
    serial = models.AutoField(_(u'Serial'), null=False, blank=False, unique=True, db_index=True, primary_key=True)
    validade = models.DateField(_(u'Validade'), auto_now=False, auto_now_add=False)
    lote = models.CharField(_(u'Lote do fabricante'), null=False, blank=False, max_length=20)
    quantidade = models.PositiveIntegerField(_(u'Quantidade'), null=False)
    mud = models.PositiveIntegerField(_(u'Menor unidade de dispensa'), null=False)
    data_entrada = models.DateField(_(u'Data de entrada'), default=timezone.now())

我的管理员应用:

def print_barcode(modeladmin, request, queryset):
    path_output = os.path.join(settings.MEDIA_ROOT, Entrada.serial)
    cmd = settings.BARCODE_COMMAND.format(Entrada.serial, path_output)


class EntradaAdmin(admin.ModelAdmin):
    list_display = ['medicamento_descricao', 'serial', 'quantidade', 'medicamento_estoque', 'data_entrada', 'usuario']
    search_fields = ['medicamento__descricao']
    action = [print_barcode]

    class Meta:
         model = Entrada

1 个答案:

答案 0 :(得分:2)

看起来你正试图从CLASS模型中获取一个属性。您需要做的是从该模型类的实例化中获取属性。

model_obj = Entrada.objects.get(id=some_id)

def print_barcode(modeladmin, request, queryset):
    path_output = os.path.join(settings.MEDIA_ROOT, model_obj.serial)
    cmd = settings.BARCODE_COMMAND.format(model_obj.serial, path_output)