Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Django 1.6.x how to get data of associated models in views?

After so much googling I did'nt found any relevant solution for getting the associated models data in views.

Things is I am requesting to the server via Ajax and want to fetch the folders and folder creator name(from User model). But it did'nt return me the first_name of the creator. Here's the code

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)

I have tried .select_related('creator') too but it did'nt work.

In js I am fetching the data like this :

$.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 always return undefined.

Any help would be really appreciated.

Thanks

like image 774
Arjun Thakur Avatar asked Nov 10 '22 21:11

Arjun Thakur


1 Answers

You can always create a dictionary of the data you want to use on your client side:

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)

And in your js:

t = t.replace(/\{(C_ID)\}/g, v.creator__first_name); 
like image 179
nima Avatar answered Nov 14 '22 22:11

nima