Coder949
Coder949

Reputation: 1007

Is it possible to call an Django Foreign Key object in success of Ajax?

Is it possible to call an Django Foreign Key object in success of Ajax ?

models.py

class Message(models.Model):
id = models.AutoField(primary_key=True)
chat = models.ForeignKey(Chat, models.CASCADE, null=True, related_name='chat')
message = models.CharField(max_length=5000)
date = models.DateTimeField(auto_now_add=True)

views.py

def message_view(request):
    chatid = request.GET.get('chatid', None)
    messages =  Message.objects.filter(chat__id=chatid)
    message_list = list(messages.values())

    data = { 'message_list': message_list }
    return JsonResponse(data)

chatoverview.html

 $(document).ready(function(){
                $(".btn_load_messages").click(function(){
                    var chatid = $(this).val();

                    $.ajax({
                        url:'/ajax/messages',
                        data: {
                            'chatid': chatid
                        },
                        dataType: 'json',
                        success: function(data){
                                var message_list = data.message_list;
                                var requestuser = "{{ request.user.id }}"
                                $(".container-text2").empty();
                                $.each(message_list, function(index, value){
                                    $(".container-text2").
                                  append("<div class=text1>"+ value.message +"</div>"); 
                                });                             
                        }
                    });
                });
            });

I need the chat.buyer.id. So i would do something like:

 $(".container-text2").append("<div class=text1>"+ value.chat.buyer.id +"</div>");

But this does not work. Is it possible to do something like this ? If yes, could you please tell me what i have to change to get it working ?

Upvotes: 0

Views: 979

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599580

No, you can't do this. Even if the JS somehow knew about your models, it wouldn't be able to access the data because it is running on the browser, not the server.

You need to supply all the information you need in your JsonResponse. You could build up the data manually via for loops or list comprehensions; alternatively, if you are doing a lot of this kind of thing, you should investigate django-rest-framework, whose serializers allow you to customise the JSON representation of your models.

Upvotes: 1

Related Questions