Issue
How can I get value from class django.db.models.fields.IntegerField?
I want get 1 from admin field.
This is python code: model class and function view
from django.db import models
from django.db import connection
import pymysql
# Create your models here.
class Users(models.Model):
def __init__(self,*args, **kwargs):
super().__init__(*args, **kwargs)
self.firstname=models.CharField(max_length=100)
self.lastname=models.CharField(max_length=100)
self.username=models.CharField(max_length=50)
self.password=models.CharField(max_length=255)
self.admin=models.IntegerField()
self.createdAt=models.DateTimeField(db_column="created_at")
def getAdmin(self):
return self.admin
class Meta:
db_table = 'users'
A view function when I run user = Users.objects.get(id=userId)
def home(request):
#controllo se sei loggato
if request.session.has_key('loggedin'):
if request.session['loggedin'] != True:
return redirect("login")
else:
return redirect("login")
#l'utente รจ loggato recupero le informazioni
userId = int(request.session['id'])
user = Users.objects.get(id=userId)
print(type(user))
print(type(user.getAdmin()))
tmplVar = {}
tmplVar["admin"] = user.admin
return render(request, 'pygiustizia/home.html',{'tmplVar': tmplVar})
Solution
I presume, you want the value of admin. From my understanding what you can do is you can use filter method on you object inside your Users
model. As you have intialized the model fields inside the __init__
method, that I am sure is not a good practice, but based on your requirement here you can do:
from django.db import models
# Create your models here.
class Users(models.Model):
def __init__(self,*args, **kwargs):
super().__init__(*args, **kwargs)
self.firstname=models.CharField(max_length=100)
self.lastname=models.CharField(max_length=100)
self.username=models.CharField(max_length=50)
self.password=models.CharField(max_length=255)
self.admin=models.IntegerField()
self.createdAt=models.DateTimeField(db_column="created_at")
def getAdmin(self):
return self.objects.get(admin=self.admin)
class Meta:
db_table = 'users'
Then you can replace your line user = Users.objects.get(id=userId)
with
user = User(userId)
I hope this is what you are looking for!
Answered By – trojanatwar
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0