本文介绍了模型对象中的Django UnicodeDecodeError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我正在django中处理的另一个UnicodeDecodeError.我找不到解决方法.

this is another UnicodeDecodeError I'm dealing with in django. I can't find the way to solve it.

我正在尝试创建一个对象:

I'm trying to create an object:

nivel_obj = Nivel.objects.filter(id=nivel_id)
nueva_matricula = Matricula(nivel=nivel_obj, ano_lectivo=ano_lectivo, alumno=a)
nueva_matricula.save()

矩阵"对象具有作为外键的"nivel_obj"."nivel_obj"的名称是无法编码/解码的字符串.

The "Matricula" object has a "nivel_obj" that is a Foreign Key. The "nivel_obj" has a name that is a string that could not be encoded/decoded.

我该如何解决?

这些是模型:

class Nivel(models.Model):
    """
    Ej - "Octavo de Basica, 6to Curso"
    """
    nombre = models.CharField(max_length=150)

    class Meta:
        verbose_name_plural = "niveles"

    def __unicode__(self):
        return u"%s" % (self.nombre)


class Matricula(models.Model):
    ano_lectivo = models.PositiveIntegerField(validators=[MaxValueValidator(9999)])
    alumno = models.ForeignKey(Alumno)
    nivel = models.ForeignKey(Nivel, null=True) <----
    status = models.CharField(max_length=150, choices=(("A", "Activo"), ("I", "Inactivo")))

    def validate_unique(self, exclude=None):
        if Matricula.objects.filter(alumno=self.alumno, nivel=self.nivel, ano_lectivo=self.ano_lectivo).exists():
            error = u'Ya existe una matrícula igual, por favor revisa el año, el nivel y el alumno'
            raise ValidationError({NON_FIELD_ERRORS: error})
        else:
            pass

    class Meta:
        verbose_name_plural = "matrículas"
        verbose_name = "matrícula"

        ordering = ("alumno",)

    def __unicode__(self):
        return u"Matricula %s %s" % (self.alumno, self.ano_lectivo)

确切的错误来自一个名为"Nivel"的对象,该对象的名称类似于"Octavo deBásica",如果没有UnicodeDecodeError,我将无法使用它.

The exact error comes from a "Nivel" object that has a name like this "Octavo de Básica", I can't work with it without having a UnicodeDecodeError.

这是错误:

UnicodeDecodeError at /sisacademico/matricular_grupo/

'ascii' codec can't decode byte 0xc3 in position 20: ordinal not in range(128)

...

The string that could not be encoded/decoded was: de B��sica

发现错误

好,我发现了我的错误,我不会删除导致django给我的错误(UnicodeDecodeError)的问题,这是完全令人误解的问题.错误是这个:

OK I found my error, I'm not going to delete the question cause the error (UnicodeDecodeError) django was giving me is completely misleading. The error was this one:

nivel_obj = Nivel.objects.filter(id=nivel_id) <---
nueva_matricula = Matricula(nivel=nivel_obj, ano_lectivo=ano_lectivo, alumno=a)

我无法使用nivel = queryset而不是nivel = NivelObject保存新对象.

I cannot save a new object with a nivel=queryset and not nivel=NivelObject.

应为:

nivel_obj = Nivel.objects.get(id=nivel_id)

我的错误.

但是,为什么地球会让django给我UnicodeDecodeError?!

BUT, WHY ON EARTH would django give me a UnicodeDecodeError?!!

推荐答案

过滤器并未在此处执行您想要的操作:

filter isn't doing what you want it to here:

nivel_obj = Nivel.objects.filter(id=nivel_id)

filter 返回一个查询集,而不是单个对象.您不能将其用作 ForeignKey 字段的值.我还不明白为什么这会引发您报告的异常,也许是在尝试报告异常时无法正确分类的东西?

filter returns a queryset, not a single object. You can't use it as the value of the ForeignKey field. I don't yet see why that would raise the exception you're reporting, maybe something not stringifying correctly while it's trying to report the exception?

通常,您将使用 get 获取单个对象而不是查询集,或者在视图中有时使用 get_object_or_404 快捷方式.但是,您不必仅设置外键关系就可以执行此操作-您可以直接使用ID值进行实例化:

Normally you'd use get to get a single object rather than a queryset, or in a view sometimes the get_object_or_404 shortcut. But you don't need to do that just to set a foreign key relationship - you can instantiate directly with the ID value:

nueva_matricula = Matricula(nivel_id=nivel_id, ano_lectivo=ano_lectivo, alumno=a)
nueva_matricula.save()

如果您的错误仍然存​​在,我将专注于检查 self.nombre 的返回类型.Django CharField s应该始终返回Unicode对象,但是如果您发生了一些真正不规范的事情,并且您得到的编码字节串为 nombre ,则您的 __ unicode__方法将抛出显示的 UnicodeDecodeError .但这对于标准Django来说是不可能的.

If your error persists, I would focus on checking the return type of self.nombre. Django CharFields should always return a Unicode object, but if you've got something really nonstandard happening and you're getting an encoded bytestring as nombre, your __unicode__ method will throw the UnicodeDecodeError shown. But that shouldn't be possible with standard Django.

这篇关于模型对象中的Django UnicodeDecodeError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 22:29