Hi list !
Exercise :
Consider the following code : How would you write BaseModel::get_class_of ?
Simply put :
I have Country class and a City class.
I want to pass this assert :
assert City.get_class_of("country_id") == Country
Put another way : how can I access the class that the country_id attribute
referes to ?
<code>
from elixir import *
class MetaModel(EntityMeta):
def __call__(cls,*args,**kw):
id = kw.get("id")
instance = None
# Is this an edit ?
if id :
instance = cls.get(id).one()
instance.from_dict(kw)
# or a creation ?
else:
instance = type.__call__(cls,*args,**kw)
for key in kw:
if key.endswith("_id"):
relation_class = instance.get_class_of(key)
relation_id = kw[key]
set_attribute(instance,key,relation_class.get(relation_id))
return instance
class BaseModel(Entity):
using_options(abstract=True)
repr_attr = "name"
def __repr__(self):
"""
"""
return "<%s '%s' id='%s'>" %
(self.__class__.__name__,getattr(self,self.repr_attr,id(self)),self.id)
def get_class_of(relation_name):
"""
self.get_class_of("country_id") == Country
"""
# How do I write this ? can self.mapper.get_property(relation_name)
lead to the relation's class ?
pass
class Country(BaseModel):
"""
"""
using_options(tablename = "countries")
name = Field(String)
cities = OneToMany("City")
class City(BaseModel):
"""
"""
using_options(tablename = "cities")
name = Field(String)
country = ManyToOne("Country")
# After elixir setup
algeria = Country("Algeria")
session.flush()
algiers = City("Algiers",country_id=algeria.id)
# The purpose of all this is to have algiers.country == algeria, merely by
passing country_id to City.
print algiers.country
# Should print :
# > <Country 'Algiers' id='1'>
</code>
--
You received this message because you are subscribed to the Google Groups
"SQLElixir" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/sqlelixir?hl=en.