Update queryset on view without actually updating on databaseHow do I check whether a file exists without exceptions?How to combine 2 or more querysets in a Django view?How to print without newline or space?How do I do a not equal in Django queryset filtering?django - inlineformset_factory with more than one ForeignKeyShow information of subclass in list_display djangoProducts catalogue: filter by parametersRadio buttons in django adminLoop inside loop in queryset in Django templateHow to define Mode with generic ForeignKey in Django

Can you create a free-floating MASYU puzzle?

Can the Four Elements monk's Shape the Flowing River elemental discipline create stairs by expending a single ki point?

What factors could lead to bishops establishing monastic armies?

Category-theoretic treatment of diffs, patches and merging?

Floating Pumice Road. Slab Size

Why is whale hunting treated differently from hunting other animals?

How was the website able to tell my credit card was wrong before it processed it?

What are the consequences for a developed nation to not accept any refugee?

Passwordless authentication - how invalidate login code

Why do people prefer metropolitan areas, considering monsters and villains?

Why did the frequency of the word "черт" (devil) in books increase by a few times since the October Revolution?

Can one block with a protection from color creature?

Can a USB hub be used to access a drive from two devices?

Difference between [[ expr1 || expr2 ]] and [[ expr1 ]] || [[ expr2 ]]

How to evaluate the performance of open source solver?

I don't want to be introduced as a "Minority Novelist"

How do I talk to my wife about unrealistic expectations?

As a supervisor, what feedback would you expect from a PhD who quits?

Gory anime with pink haired girl escaping an asylum

Array or vector? Two dimensional array or matrix?

What does "spinning upon the shoals" mean?

NOLOCK or Read Uncommitted locking / latching behaviours

How do ballistic trajectories work in a ring world?

Why do airports remove/realign runways?



Update queryset on view without actually updating on database


How do I check whether a file exists without exceptions?How to combine 2 or more querysets in a Django view?How to print without newline or space?How do I do a not equal in Django queryset filtering?django - inlineformset_factory with more than one ForeignKeyShow information of subclass in list_display djangoProducts catalogue: filter by parametersRadio buttons in django adminLoop inside loop in queryset in Django templateHow to define Mode with generic ForeignKey in Django






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








1















I'm trying to add a field "grade" to my users queryset. I have 3 models: Users, Subject and Exam. I don't think there is a way to calculate a user grade on the initial query like:



Users.objects.get(pk=x).annotate(grade=z)


because I have to call a method of the Subject model to calculate the total grade of that user for the subject, not only the grade for 1 exam (see the method below in the models description).



In my view I did:



user_obj = Users.object.get(pk=x).annotate(grade=Value(0, IntegerField()))
calculated_grade = subject.calculate_user_grade(user_obj)
user_obj.grade = calculated_grade


And then passed the user_obj to the template. But once it gets there the grade field I modified is already gone. I print "user_obj.grade" on view and it gives the correct value, then I print it on the template and it gives me 0, the initial value of the "annotate".



The models I use are the default user model in django and then



class Subject(models.Model):
name = models.CharField()

def calculate_user_grade(self, user):
points = 0
exams = Exam.objects.filter(subject=self)
for exam in exams:
user_answer = ExamUser.objects.get(user=user, exam=exam)
points += user_answer.points
return points

class Exam(models.Model):
subject = models.ForeignKey(Subject)
question = models.CharField()

class ExamUser(models.Model):
exam = models.ForeignKey(Exam)
user = models.ForeignKey(User)
points = models.PositiveIntegerField(default=0)










share|improve this question
























  • How do you pass the user_obj to the template? Can you show more of the view?

    – c6754
    Mar 25 at 21:34


















1















I'm trying to add a field "grade" to my users queryset. I have 3 models: Users, Subject and Exam. I don't think there is a way to calculate a user grade on the initial query like:



Users.objects.get(pk=x).annotate(grade=z)


because I have to call a method of the Subject model to calculate the total grade of that user for the subject, not only the grade for 1 exam (see the method below in the models description).



In my view I did:



user_obj = Users.object.get(pk=x).annotate(grade=Value(0, IntegerField()))
calculated_grade = subject.calculate_user_grade(user_obj)
user_obj.grade = calculated_grade


And then passed the user_obj to the template. But once it gets there the grade field I modified is already gone. I print "user_obj.grade" on view and it gives the correct value, then I print it on the template and it gives me 0, the initial value of the "annotate".



The models I use are the default user model in django and then



class Subject(models.Model):
name = models.CharField()

def calculate_user_grade(self, user):
points = 0
exams = Exam.objects.filter(subject=self)
for exam in exams:
user_answer = ExamUser.objects.get(user=user, exam=exam)
points += user_answer.points
return points

class Exam(models.Model):
subject = models.ForeignKey(Subject)
question = models.CharField()

class ExamUser(models.Model):
exam = models.ForeignKey(Exam)
user = models.ForeignKey(User)
points = models.PositiveIntegerField(default=0)










share|improve this question
























  • How do you pass the user_obj to the template? Can you show more of the view?

    – c6754
    Mar 25 at 21:34














1












1








1








I'm trying to add a field "grade" to my users queryset. I have 3 models: Users, Subject and Exam. I don't think there is a way to calculate a user grade on the initial query like:



Users.objects.get(pk=x).annotate(grade=z)


because I have to call a method of the Subject model to calculate the total grade of that user for the subject, not only the grade for 1 exam (see the method below in the models description).



In my view I did:



user_obj = Users.object.get(pk=x).annotate(grade=Value(0, IntegerField()))
calculated_grade = subject.calculate_user_grade(user_obj)
user_obj.grade = calculated_grade


And then passed the user_obj to the template. But once it gets there the grade field I modified is already gone. I print "user_obj.grade" on view and it gives the correct value, then I print it on the template and it gives me 0, the initial value of the "annotate".



The models I use are the default user model in django and then



class Subject(models.Model):
name = models.CharField()

def calculate_user_grade(self, user):
points = 0
exams = Exam.objects.filter(subject=self)
for exam in exams:
user_answer = ExamUser.objects.get(user=user, exam=exam)
points += user_answer.points
return points

class Exam(models.Model):
subject = models.ForeignKey(Subject)
question = models.CharField()

class ExamUser(models.Model):
exam = models.ForeignKey(Exam)
user = models.ForeignKey(User)
points = models.PositiveIntegerField(default=0)










share|improve this question
















I'm trying to add a field "grade" to my users queryset. I have 3 models: Users, Subject and Exam. I don't think there is a way to calculate a user grade on the initial query like:



Users.objects.get(pk=x).annotate(grade=z)


because I have to call a method of the Subject model to calculate the total grade of that user for the subject, not only the grade for 1 exam (see the method below in the models description).



In my view I did:



user_obj = Users.object.get(pk=x).annotate(grade=Value(0, IntegerField()))
calculated_grade = subject.calculate_user_grade(user_obj)
user_obj.grade = calculated_grade


And then passed the user_obj to the template. But once it gets there the grade field I modified is already gone. I print "user_obj.grade" on view and it gives the correct value, then I print it on the template and it gives me 0, the initial value of the "annotate".



The models I use are the default user model in django and then



class Subject(models.Model):
name = models.CharField()

def calculate_user_grade(self, user):
points = 0
exams = Exam.objects.filter(subject=self)
for exam in exams:
user_answer = ExamUser.objects.get(user=user, exam=exam)
points += user_answer.points
return points

class Exam(models.Model):
subject = models.ForeignKey(Subject)
question = models.CharField()

class ExamUser(models.Model):
exam = models.ForeignKey(Exam)
user = models.ForeignKey(User)
points = models.PositiveIntegerField(default=0)







python django django-queryset django-orm






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 26 at 2:38









tim

9319 silver badges31 bronze badges




9319 silver badges31 bronze badges










asked Mar 25 at 21:13









TomasRezendeTomasRezende

162 bronze badges




162 bronze badges












  • How do you pass the user_obj to the template? Can you show more of the view?

    – c6754
    Mar 25 at 21:34


















  • How do you pass the user_obj to the template? Can you show more of the view?

    – c6754
    Mar 25 at 21:34

















How do you pass the user_obj to the template? Can you show more of the view?

– c6754
Mar 25 at 21:34






How do you pass the user_obj to the template? Can you show more of the view?

– c6754
Mar 25 at 21:34













1 Answer
1






active

oldest

votes


















0














A good question. From your question and codes, the issues is probably from parsing the unsaved object from view to template.



The short answer is to use dictionary instead of parsing the unsaved object.



user_obj = Users.object.get(pk=x)
calculated_grade = subject.calculate_user_grade(user_obj)
user_dict = dict(user_obj)
user_dict.setdefault('grade', calculated_grade)


Then parse the user_dict to your template.






share|improve this answer






















    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55346492%2fupdate-queryset-on-view-without-actually-updating-on-database%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    A good question. From your question and codes, the issues is probably from parsing the unsaved object from view to template.



    The short answer is to use dictionary instead of parsing the unsaved object.



    user_obj = Users.object.get(pk=x)
    calculated_grade = subject.calculate_user_grade(user_obj)
    user_dict = dict(user_obj)
    user_dict.setdefault('grade', calculated_grade)


    Then parse the user_dict to your template.






    share|improve this answer



























      0














      A good question. From your question and codes, the issues is probably from parsing the unsaved object from view to template.



      The short answer is to use dictionary instead of parsing the unsaved object.



      user_obj = Users.object.get(pk=x)
      calculated_grade = subject.calculate_user_grade(user_obj)
      user_dict = dict(user_obj)
      user_dict.setdefault('grade', calculated_grade)


      Then parse the user_dict to your template.






      share|improve this answer

























        0












        0








        0







        A good question. From your question and codes, the issues is probably from parsing the unsaved object from view to template.



        The short answer is to use dictionary instead of parsing the unsaved object.



        user_obj = Users.object.get(pk=x)
        calculated_grade = subject.calculate_user_grade(user_obj)
        user_dict = dict(user_obj)
        user_dict.setdefault('grade', calculated_grade)


        Then parse the user_dict to your template.






        share|improve this answer













        A good question. From your question and codes, the issues is probably from parsing the unsaved object from view to template.



        The short answer is to use dictionary instead of parsing the unsaved object.



        user_obj = Users.object.get(pk=x)
        calculated_grade = subject.calculate_user_grade(user_obj)
        user_dict = dict(user_obj)
        user_dict.setdefault('grade', calculated_grade)


        Then parse the user_dict to your template.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 25 at 21:27









        timtim

        9319 silver badges31 bronze badges




        9319 silver badges31 bronze badges


















            Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







            Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55346492%2fupdate-queryset-on-view-without-actually-updating-on-database%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

            용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

            155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해