I need to find a way how to append a person (form inputs I got) to a list. I always get:<main.List object at 0x0000027FD63B6B60>
class Person:
def __init__(self, name, surname, age, phone_number):
self.name = name
self.surname = surname
self.age = age
self.phone_number = phone_number
def __str__(self):
return f"\n{self.name} " + f"\t" + f"{self.surname} " + f"\t" + f"{self.age} " + f"\t" + f"{self.phone_number} "
class Input:
def __init__(self):
pass
def input_data(self):
self.name = input("\nInsert a name: \n")
self.surname = input("Insert a surname: \n")
self.age = int(input("Insert an age: \n"))
self.phone_number = input("Insert a phone number: \n")
person = NewPerson(self.name, self.surname, self.age, self.phone_number)
return person
class List:
def __init__(self):
pass
def data_to_list(self, name, surname, age, phone_number):
self.name = name
self.surnam = surnam
self.age = age
self.phone_number = phone_number
list= []
list = list.extend(self.name, self.surname, self.age, self.phone_number)
return list
First, don't use variable names named after Python's built-ins (list), use lst for example.
Also, list.extend always returns None so there's no point to assign the return value to a variable.
In constructor of class List assign to self an empty list and in method data_to_list() use list.append to put newly crated Person() to a list.
For example:
class Person:
def __init__(self, name, surname, age, phone_number):
self.name = name
self.surname = surname
self.age = age
self.phone_number = phone_number
def __repr__(self):
return f"Person({self.name}, {self.surname}, {self.age}, {self.phone_number})"
class List:
def __init__(self):
self.lst = []
def data_to_list(self, name, surname, age, phone_number):
self.name = name
self.surname = surname
self.age = age
self.phone_number = phone_number
self.lst.append(
Person(self.name, self.surname, self.age, self.phone_number)
)
l = List()
l.data_to_list("John", "Smith", "33", "+123456")
l.data_to_list("Alice", "Green", "32", "+654321")
print(l.lst)
Prints:
[Person(John, Smith, 33, +123456), Person(Alice, Green, 32, +654321)]
Related
I'm new in django. I'm trying to run my code but give me the following error: TypeError: unhashable type: 'dict'.
I'm checking all code but I don't understand where is the mistake. Moreover I don't sure about the correctness of my code. Could you give me the necessary supports?
Here my models.py
class MaterialeManager(models.Manager):
def get_queryset(self, *args, **kwargs):
return super().get_queryset(*args, **kwargs).annotate(
total=F('quantita')*F('prezzo'),
)
def get_monthly_totals(self):
conto = dict((c.id, c) for c in Conto.objects.all())
return list(
(conto, datetime.date(year, month, 1), totale)
for conto_id, year, month, totale in (
self.values_list('conto__nome', 'data__year', 'data__month')
.annotate(totale=Sum(F('quantita') * F('prezzo')))
.values_list('conto__nome', 'data__year', 'data__month', 'totale')
))
class Conto(models.Model):
nome=models.CharField('Nome Conto', max_length=30, blank=True, default="")
def __str__(self):
return self.nome
class Materiale(models.Model):
conto = models.ForeignKey(Conto, on_delete=models.CASCADE,)
tipologia = models.ForeignKey(Tipologia, on_delete=models.CASCADE,)
sottocategoria = models.ForeignKey(Sottocategoria, on_delete=models.CASCADE, null=True)
um = models.CharField()
quantita=models.DecimalField()
prezzo=models.DecimalField()
data=models.DateField('Data di acquisto', default="GG/MM/YYYY")
objects=MaterialeManager()
def __str__(self):
return str(self.sottocategoria)
and here my views.py:
def conto_economico(request):
defaults = list(0 for m in range(12))
elements = dict()
for conto, data, totale in Materiale.objects.get_monthly_totals():
if conto not in elements:
elements[conto.id] = list(defaults)
index = data.month - 1 # jan is one, but on index 0
elements[conto.id][index] = totale
context= {'elements': elements,}
return render(request, 'conto_economico/conto_economico.html', context)
You are trying to use a dict:conto as a key to your elements dictionary. That won't work because dictionary keys have to be hashable, which isn't the case. You can use other representative of cont as key, such as its name or id.
class Grade(models.Model):
name = models.CharField(u'年级', max_length=64)
school = models.ForeignKey('School', verbose_name=u'学校')
def __unicode__(self):
return self.name
class Class(models.Model):
name = models.CharField(u'班级', max_length=64)
grade = models.ForeignKey('Grade', verbose_name=u'年级', related_name='grade')
def getGradeName(self):
return self.grade.name
def __unicode__(self):
return self.name
class Student(models.Model):
name = models.CharField(u'姓名', max_length=64)
sex = models.CharField(u'性别', max_length=64)
id_num = models.CharField(u'身份证号', max_length=64)
student_num = models.CharField(u'学号', max_length=64)
class_id = models.ForeignKey('Class', verbose_name=u'班级', related_name='class_id')
grade = class_id.name
def __unicode__(self):
return self.name
I want to get students'class'grade and then assign it to grade in Model Student.
How to get Grade's name in model Student?
Since grade is going to be that of the Class instance of Student, I would suggest removing the grade class variable from Student and instead adding a property to the class Student. Like this.
class Student(models.Model):
name = models.CharField(u'姓名', max_length=64)
sex = models.CharField(u'性别', max_length=64)
id_num = models.CharField(u'身份证号', max_length=64)
student_num = models.CharField(u'学号', max_length=64)
class_id = models.ForeignKey('Class', verbose_name=u'班级', related_name='class_id')
def __unicode__(self):
return self.name
#property
def grade_name(self):
return self.class.grade.name
And to get the grade of a Student instance, it would be
student = Student.object.all()[0]
grade = student.grade_name
#get first student in table
s = Student.object.all()[0]
# get Grade access through Class model
print s.class_id.grade
Question
If istek.yorumlar_set.all reach at Istek.hedef I want change Istek.publish value to false
But, How do this is :D
If yours want to other models, i do upload
Model file :
class Istek(models.Model):
publish = models.BooleanField(default=True)
baslik = models.CharField(max_length=50)
zaman = models.DateTimeField(auto_now_add=True,editable=False)
kime = models.CharField(max_length=100)
sebep = models.CharField(max_length=30)
aciklama = models.TextField(max_length=500)
hangidua = models.ForeignKey(Dualar)
slug = models.SlugField(unique=True,editable=False)
hedef = models.IntegerField(help_text="Toplam da kaç dua istiyorsunuz : ")
def __str__(self):
return self.baslik
def save(self,*args , **kwargs):
self.slug = slugify(self.baslik)
super(Istek,self).save()
class Yorumlar(models.Model):
isim = models.CharField(max_length=50)
email = models.EmailField(max_length=50,null=True,blank=True)
websitesi = models.URLField(max_length=50,null=True,blank=True)
yorum = models.TextField()
dua = models.ForeignKey(Istek)
zaman = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return self.yorum
def __str__(self):
return self.isim+" : " +self.websitesi
class Meta:
ordering = ['zaman']
I'm not sure I understand your question. Is this what you want to achieve?
class Istek(models.Model):
...
def save(self,*args , **kwargs):
if self.yorumlar_set.count() > self.hedef:
self.publish = False
...
I'm solved this problem.Used django.signals.
Here code:
#receiver(post_save,sender=Yorumlar)
def change_true_or_false(instance,created,**kwargs):
instance.dua.toplamdua += 1
if instance.dua.toplamdua > instance.dua.hedef:
instance.dua.publish = False
instance.dua.save()
else:
instance.dua.save()
Here is my model and modelmanager. I basically want to override the save method, so I can perform some operations before saving the Companymanager.
I have defined a modelmanager but its save method is not being called when I try to save the company object.
class CompanyManager(models.Manager):
"""
Custom model manager to return a random scenario
"""
def save(self, *args, **kwargs):
#User.objects.create()
#print '*args == ', *args
#print '*kwargs == ', *kwargs
#User.objects.filter()
for each in args:
print 'each=',each
class Company(models.Model):
objects =CompanyManager()
COMPANY_SIZE = (
('1-10', '1-10'),
('11-50', '11-50'),
('51-200', '51-200'),
('201-500', '200-500'),
('501-1000', '501-1000'),
('1001-5000', '1001-5000'),
('5001-10000', '5001-10000'),
('10000+', '10000+'),
)
INDUSTRY = (
('Telecom','Telecom'),
('Technology','Technology')
)
users = models.ManyToManyField(User)
description = models.CharField(max_length=500,default='')
size = models.CharField(max_length=10,choices=COMPANY_SIZE,default='1-10')
industry = models.CharField(max_length=100,choices=INDUSTRY,default='---')
url = models.URLField(max_length=200,default='')
logo = models.ImageField(upload_to='company',default='')
addr1 = models.CharField(max_length=200,default='')
addr2 = models.CharField(max_length=200,default='')
city = models.CharField(max_length=200,default='')
state = models.CharField(max_length=2,choices=STATE_CHOICES,default='')
zip_cd = models.CharField(max_length=5,default='')
phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.")
phone_number_1 = models.CharField(validators=[phone_regex], blank=True,max_length=15)
phone_number_2 = models.CharField(validators=[phone_regex], blank=True,max_length=15)
def __str__(self):
return self.name
save() is a model instance method, not a manager method. You need to move it to your model:
class Company(models.Model):
def save(self, *args, **kwargs):
#User.objects.create()
#print '*args == ', *args
#print '*kwargs == ', *kwargs
#User.objects.filter()
for each in args:
print 'each=',each
...
let sharedintance = modelmanagar()
class modelmanagar: NSObject {
var database : FMDatabase? = nil
class func getinstance() -> modelmanagar
{
if(sharedintance.database == nil)
{
let documentURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let fileURL = documentURL.appendingPathComponent("dddddbbbbbb.sqlite" as String)
sharedintance.database = FMDatabase(path:fileURL.path)
}
return sharedintance
}
#C:/Python32
class Person:
def __init__(self, name = "joe" , age= 20 , salary=0):
self.name = name
self.age = age
self.salary = salary
def __printData__(self):
return " My name is {0}, my age is {1} , and my salary is {2}.".format(self.name, self.age, self.salary)
print(Person)
class Employee(Person):
def __init__(self, name, age , salary ):
Person. __init__ (self,name = "Mohamed" , age = 20 , salary = 100000)
def __printData__(self):
return " My name is {0}, my age is {1} , and my salary is {2}.".format(sef.name, self.age, self.salary)
print(Employee)
You need to indent the second line here, from:
def __printData__(self):
return " My name is {0}, my age is {1} , and my salary is {2}.".format(sef.name, self.age, self.salary)
to:
def __printData__(self):
return " My name is {0}, my age is {1} , and my salary is {2}.".format(sef.name, self.age, self.salary)
You need to indent the second to last line because it is after a function definition. Also, at one point you use sef instead of self. I've corrected both of these below:
class Person:
def __init__(self, name = "joe" , age= 20 , salary=0):
self.name = name
self.age = age
self.salary = salary
def __printData__(self):
return " My name is {0}, my age is {1} , and my salary is {2}.".format(self.name, self.age, self.salary)
print(Person)
class Employee(Person):
def __init__(self, name, age , salary ):
Person. __init__ (self,name = "Mohamed" , age = 20 , salary = 100000)
def __printData__(self): # The problem was the line after this one.
return " My name is {0}, my age is {1} , and my salary is {2}.".format(self.name, self.age, self.salary)
print(Employee)