Home > Net >  How to get data from model fields in django?
How to get data from model fields in django?

Time:02-14

I made a patient register form. I added two patient to database. And i wanna save each patient informations to text file. And i wanna make all txt file is uniqe name. So i am using this code for save txt file;

file_name must be each patient name, and i am having problem in this line... I didnt filter or pull data from model

def deneme(request):
    
    dir_path = Path('/Users/emr/Desktop/ngsaglik/homeo/patient/templates/kayitlar')
    file_name = str(Post.objects.get(???)) # i wanna pull each patient name as a txt file name


    f = open (dir_path.joinpath(file_name),'w')
    testfile = File(f)

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

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

my models.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):
    
    
    name = models.CharField(verbose_name='Ad Soyad',max_length=10000, default="")
    surname = 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="")

CodePudding user response:

Iterate through all Post objects, and create a new file for each of them.

def deneme(request):
    
    dir_path = Path('/Users/emr/Desktop/ngsaglik/homeo/patient/templates/kayitlar')

    kayitlar = Post.objects.all()

    for kayit in kayitlar:

        file_name = str(kayit.name)
        f = open (dir_path.joinpath(file_name),'w')

        testfile = File(f)

        lines = []
        lines.append(f'{kayit.soru1}\n{kayit.soru2}\n')

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