django ForeignKey ManyToMany 前后端联动

总结

  • 外键基本和普通的字段是一样的
  • 多对多
    • 获取 getlist()
    • 更新 clear() add() remove()
  • 前端和后端是通过字符串沟通的,所以使用ajax的时候如果是数据类型,记得要JSON转换

ForeignKey

后端处理

user_types = models.UserType.objects.all()  # 在template 中使用
data_to_tpl["user_types"] = user_types



user_id = request.POST.get("id", None)
# print(type(request.POST.values()), request.POST.values())

to_update_dict = {}
to_update_dict["password"] = request.POST.get("password")
to_update_dict["phone"] = request.POST.get("phone")
to_update_dict["email"] = request.POST.get("email")
to_update_dict["user_type_id"] = request.POST.get("user_type_id")
front_hobbys = list(request.POST.getlist("hobbys"))  # 获取select widget 的数据列表,如果使用get(), 那只会得到最后一个元素
print("---front_hobbys:", front_hobbys)
print("---to_update_dict", to_update_dict)

# update
models.UserInfo.objects.filter(pk=user_id).update(**to_update_dict)
user_obj = models.UserInfo.objects.get(pk=user_id)
user_obj.hobby.clear()  # 多对多, 先清除,在添加
user_obj.hobby.add(*front_hobbys)  # 多对多, 先清除,在添加
user_obj.save()  # save to databases

模板

form 方式提交

    模板语言动态生成:
     <td>
        <select name="user_type_id">
            {% for user_type in user_types %}
                {% if user.user_type_id == user_type %}
                    <option value={{ user_type.id }} selected="selected">{{ user_type.caption }}</option>
                {% else %}
                    <option value={{ user_type.id }}>{{ user_type.caption }}</option>
                {% endif %}
            {% endfor %}
        </select>
    </td>

ajax 方式提交

这个简单,不写了

ManyToMany

后端处理

data_to_tpl["my_hobbys"] = user_obj.hobby.all()  # 注意,这里一定要有一个all出来的才是 queryset类型的数据

all_hobbys = models.Hobby.objects.all()  # 在template 中使用
data_to_tpl["all_hobbys"] = all_hobbys

# 取数据 更新
front_hobbys = list(request.POST.getlist("hobbys"))  # 注意,这里一定是getlist()
user_obj = models.UserInfo.objects.get(pk=user_id)
user_obj.hobby.clear()
user_obj.hobby.add(*front_hobbys)

模板

form 方式提交

 <tr>
    <td>爱好</td>
    <td>
        <select name="hobbys" multiple="multiple" disabled="disabled" id="hobby_select">
            {% for hobby in all_hobbys %}
                {% if hobby in my_hobbys %}
                    <option value="{{ hobby.id }}" selected="selected">{{ hobby.title }}</option>
                {% else %}
                    <option value="{{ hobby.id }}">{{ hobby.title }}</option>
                {% endif %}
            {% endfor %}
        </select>
        <a href="javascript:void(0)" onclick="deleteThisHobby(this)">编辑</a>
    </td>
</tr>

ajax 方式提交

function uploadModifiedHobby(ths) {
        var hobbys = $("#hobby_select").val();
        hobbys_str = JSON.stringify(hobbys)  // 要转换成字符串格式哦
        console.log(hobbys_str)
        $.ajax({
            type:"POST",
            url:"/chouti_like/delete_this_hobby/",
            data:{"hobbys":hobbys_str,},
            success:function (data) {
                location.href = "/chouti_like/show_my_info/"
            }
        })
    }
posted @ 2016-10-31 18:11  aomibaba  阅读(377)  评论(0编辑  收藏  举报