I have csv like this,
name,job
Jay,engineer
Kay,layer
hop,warrior
then I load this in pandas
datafrme
and put in DB
df = pd.read_csv('job.csv')
for index,row in df.iterrows():
q = Issue(name = row[0],job = row[1])
q.save()
print ("Register : ",row[0] , " / ",row[1])
exit()
It works well but now, I want to generalize this code as function like this below.
def stor_db(classname):
df = pd.read_csv(classname + '.csv')
for index,row in df.iterrows():
q = `classname`(
`title[0]ofdf` = row[0],
`title[1]ofdf` = row[1])
q.save()
print ("Register : ",row[0] , " / ",row[1])
exit()
I need to dynamically make variable/class name.
It possible for python and pandas??
Everything in Python is an object, including classes.
The builtin type() is mostly used to check a variable type but there is a least known usage. If type() is used with 3 parameters, it creates a new type Object.
The first parameter is the name of your class, the second is the tuple of bases classes for inheritance, the third is a dict that will becomes the __dict__ attribute.
Example = type("Example", (object,), {"a" : 0})
# equivalent to
class Example(object):
def __init__(self):
self.a = 0
So you can do something like that
Example = type(classname, (object,), {title[0]ofdf = row[0], title[1]ofdf = row[1]})
Inherit a base class with the needed methods instead of object and you'll have the common methods you need.
EDIT:
If your classes are Django models it completely changes the nature of the problem and this solution is not pertinent. Your models already exists so you don't really want to create classes dynamically, but pick the model dynamically.
I think I'll go with a load_from_csv method using __class__.__name_, shared via inheritance and use kwargs as parameters to the constructors (assuming the models attributes exactly match the csv columns).
Thank you very much, it is quite useful to understand. So now What I want to make is django model declared in model.py
object,class Issue(models.Model):
,So now I tried to do like this ,q = type("Issue",(models.Model,),{'name' : 'testname','job' : 'test'})
but it shows errormodule = attrs.pop('__module__') KeyError: '__module__'
Well I think going towards this way is not adapted then, see my edit.
I see.. but thanks to your answer It gave me new knowledge about python. I need to understand django framework more