django模型中是否有任何方法可用,以便我可以使用字符串访问其fieldname?

时间:2013-05-15 04:08:29

标签: python ajax django

我想使用ajax更新字段:

models.py

class EmployerInfo(models.Model):
    employer = models.ForeignKey(Employer, unique=True)
    address=models.CharField(max_length=100, blank=True)
    city=models.CharField(max_length=40, blank=True)

contactinfo.html

<form id="ajax-form">
    <fieldset> 
        <legend>Contact Information</legend> 
        <label>Address:</label> 
        <input type="text" id="address" value="{{ empinfo.address }}" />
        <label>City:</label>
        <input type="text" id="city" value="{{ empinfo.city }}" /> <i class="icon-ok"></i>
    </fieldset>
</form>
<script>

$(document).ready(function()
{
    $("form#ajax-form").find(":input").change(function()
     {
       var field_name=$(this).attr("id");
       var field_val=$(this).val();
       var params ={ param1:field_name, param2:field_val };

       $.ajax({ url: "/employer/contactinfo/save/",
                dataType: "json",
                data: params,           
                success: setResult      
             });
    });
});

urls.py

.....其他网址

url(r'^employer/contactinfo/save/$', 'save_employer_info_ajax'),

view.py

def save_employer_info_ajax(request):
    emp=Employer.objects.get(user=request.user)
    emp_info=EmployerInfo.objects.get(employer=emp)
    f_name=request.GET['param1']
    f_value=request.GET['param2']
    return HttpResponse(json.dumps({"issuccess": 'yes'}), content_type="application/json")

f_name我想要更新的字段的名称。我们假设它是“地址”。 我如何访问该属性(即emp_info.address),以便我可以使用emp_info.save()函数更新(即emp_info.address = f_value)。

是否有除emp_info.address以外的任何方法,以便我可以使用字符串(即emp_info [f_name] = f_value)或其他东西访问字段名称?

2 个答案:

答案 0 :(得分:4)

你可以使用getattr烘焙到python

attr_name = 'employer_id'

if getattr(employee, attr_name) == 3:
    ...

答案 1 :(得分:2)

您可以在queryset对象上使用update method。有点hacky,因为你真的只想更新一个对象。

def save_employer_info_ajax(request):
    emp_info_query = EmployerInfo.objects.filter(employer__user=request.user)
    update_dict = {request.GET['param1'] : request.GET['param2'] }
    emp_info_query.update(**update_dict)

请注意,我正在使用反向查询关系来根据EmployerInfo模型的user字段访问Employer。然后构建一个字典来保存您想要更新的键和值,并将其传递给 queryset 的更新方法,而不是模型实例

应该使用表单进行数据输入。应该对您输入数据库的所有字段进行验证。您可以使用dynamic forms根据您通过ajax提交的值指定要包含的字段。