Django:AttributeError:'unicode'对象没有属性'对象'

时间:2015-11-15 15:06:11

标签: python django unicode

views.py:

def submit_upload(request,):

    if request.method == 'POST': 
        form = AerialForm(request.POST)
        id_key = form.data['id_key']
        year_id = form.data['year_id']
        year = Year.objects.get(year_id=year_id)

        series_id = form['series_id'].value()
        q_series = Series.objects.get(series_id=series_id)
        s_name = q_series.series.lower()

        table_name = s_name+'_photocenter_'+year.year_name

        query = table_name.objects.filter(ID_KEY=id_key)

从上面的代码中,我想从query获取值,当我运行代码时,我收到此错误:

    query = table_name.objects.filter(ID_KEY=id_key)

AttributeError: 'unicode' object has no attribute 'objects'

2 个答案:

答案 0 :(得分:2)

动态加载模型使用:

Django 1.7 +

from django.db.models.loading import get_model
Model = get_model('your_app_name', table_name)

年长的Django

try:
    from django.apps import apps
    Model = apps.get_model(app_label='your_app_name', model_name=table_name)
except ImportError:
    from django.db.models.loading import get_model
    Model = get_model('your_app_name', table_name)

通用

{{1}}

答案 1 :(得分:1)

欢迎使用Stackoverflow :)

table_name应该是型号名称。在你的情况下,它只是一个unicode对象

你需要什么样的(积分去托马斯)

from django.apps import apps

model_name = '%s_photocenter_%s' % (s_name, year.year_name)
YourModel = apps.get_model(app_label='your_app_name', model_name=model_name)