Home > Net >  Getting <django.db.models.query_utils.DeferredAttribute object at 0x1069ce0d0> instead of valu
Getting <django.db.models.query_utils.DeferredAttribute object at 0x1069ce0d0> instead of valu

Time:02-14

I wanna write all model fields to text file but i am getting this. How can i fix this. I am making patient register form and after register i wanna see all model fiels on the text file. This code works, i am getting text file but instead of value i have a deferredattribute. Where is my fault?

This is my model.py

from django.db import models
from django.contrib.auth.models import User
from django.urls import reverse
#from datetime import datetime, date

class Post(models.Model):
    
    #post_date = models.DateField(auto_now_add = True)
    soru1 = models.CharField(verbose_name='Ad Soyad',max_length=10000, default="")
    soru2 = models.CharField(verbose_name='Tarih', max_length=10000, default="")
    soru3 = models.CharField(verbose_name='Doğum Tarihi', max_length=10000, default="")
    soru4 = models.CharField(verbose_name='Doğum Yeri', max_length=10000, default="")
    soru5 = models.CharField(verbose_name='Medeni Hali', max_length=10000, default="")

This is my views.py

from django.shortcuts import render
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView
from .models import Post
from .forms import PostForm
from django.urls import reverse_lazy
from django.db.models import Q
from django.http import HttpResponse
from django.core.files import File



#Dosya Kaydetme

def writetofile(request):
    f = open('/Users/emr/Desktop/ngsaglik/homeo/patient/templates/kayitlar/test.txt', 'w')
    testfile = File(f)

    kayitlar = Post.objects.all()
    lines = []
    for kayit in kayitlar:
        lines.append(f'{Post.soru1}')

    testfile.write(str(lines))
    testfile.close
    f.close
    return HttpResponse()

And here is the result

['<django.db.models.query_utils.DeferredAttribute object at 0x1069ce0d0>', '<django.db.models.query_utils.DeferredAttribute object at 0x1069ce0d0>']

CodePudding user response:

You have to change Post.soru1 to kayit.soru1. It is because Post is call to the class, not instance you want to get in this case, that's why it shows only the model field instead of an instance's value.

kayitlar = Post.objects.all() here you assigned the all existing instances of Post model to variable kayitlar. Now you can forget about Post and process further the kayitlar variable with all objects.

  • Related