【问题标题】:is there any method available in django models, so that i can access its fieldname using string?django 模型中是否有可用的方法,以便我可以使用字符串访问其字段名?
【发布时间】:2013-05-15 04:08:28
【问题描述】:

我想使用 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 )或其他方式访问字段名称??

【问题讨论】:

    标签: python ajax django


    【解决方案1】:

    你可以只使用在 python 中烘焙的 getattr

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

    【讨论】:

    • 它有效。我猜到并使用 setattr()(ie setattr(emp_info, f_name) == f_value) 来设置值,它也可以工作。谢谢
    • 如果你想编辑内存模型实例而不是使用 update 直接更新数据库,则依次设置attr。
    【解决方案2】:

    您可以在查询集对象上使用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)
    

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

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

    【讨论】:

    • 我只需要更新一个字段,所以我使用 setattr()(ie setattr(emp_info, f_name) == f_value) 来设置值
    猜你喜欢
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-11
    • 2020-07-22
    • 2021-05-03
    相关资源
    最近更新 更多