在Django 1.6.x中如何获取视图中关联模型的数据?

时间:2014-12-26 05:51:24

标签: python ajax django associations

经过如此多的谷歌搜索后,我没有找到任何相关的解决方案来获取视图中的关联模型数据。

事情是我通过Ajax向服务器请求并且想要获取文件夹和文件夹创建者名称(来自用户模型)。但它并没有让我成为创作者的第一个名字。这是代码

models.py

class UserFolder(models.Model):
    creator = models.ForeignKey(User)
    name = models.CharField(blank=False, max_length=150)
    is_shared = models.BooleanField(default=False)
    created_date = models.DateTimeField(auto_now_add=True)
    modified_date = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name

views.py

def pagination(obj, request):
    max = request.GET.get('max') if 'max' in request.GET else 1
    paginator = Paginator(obj, max)  # Show 25 contacts per page
    page = request.GET.get('page')
    try:
        return paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        return paginator.page(1)
    except EmptyPage:
        return ""

def folder_list(request):   #called via ajax
    folders = UserFolder.objects.filter(creator=request.user.id).order_by('-modified_date')
    folders = pagination(folders, request) #for pagination
    folders = json.dumps({}) if not folders else serializers.serialize("json", folders)
    return HttpResponse(folders)

我也尝试了 .select_related('creator'),但它确实没有用。

在js中,我正在获取这样的数据:

$.each(data, function(i, v) {
                        var t = fldrTpl, id = v.pk;
                        v = v.fields
                        t = t.replace(/\{(ID)\}/g, id);
                        t = t.replace(/\{(NAME)\}/g, v.name);
                        t = t.replace(/\{(C_SIZE)\}/g, (v.current_size == null?0:v.current_size));
                        t = t.replace(/\{(C_ID)\}/g, v.creator.first_name); 
                        t = t.replace(/\{(C_DATE)\}/g, v.created_date);
                        $(".my-folder-table").append(t);
                    });

v.creator.first_name 始终返回undefined。

任何帮助都会非常感激。

由于

1 个答案:

答案 0 :(得分:1)

您始终可以在客户端创建要使用的数据字典:

def folder_list(request):   #called via ajax
    folders_obj = UserFolder.objects.filter(creator=request.user).select_related('creator').order_by('-modified_date').all()
    folders_dict = [] 
    for folder in folders_obj:
        d = {}
        for k, v in folder.__dict__.items():
            d[k] = str(v)
        d["creator__first_name"] = folder.creator.first_name
        folders_dict.append(d)
    folders = pagination(folders_dict, request) #for pagination
    folders = json.dumps({}) if not folders else serializers.serialize("json", folders)
    return HttpResponse(folders)

在你的js:

t = t.replace(/\{(C_ID)\}/g, v.creator__first_name);