Reputation: 6905
I have two tables from a legacy database imported to my django app using inspectdb
Here is my model definition
class AppCosts(models.Model):
cost = models.DecimalField(max_digits=10, decimal_places=2)
class AppDefinitions(models.Model):
data = models.TextField()
permissions = models.CharField(max_length=50, blank=True)
appcost=models.OneToOneField(AppCosts, db_column='id')
Every app in AppDefinitions has one entry in AppCosts - a one to one relationship
When I use select_related() I get :
>>> AppDefinitions.objects.select_related().query.__str__()
u'SELECT _app_definitions.id, _app_definitions.data,
_app_definitions.permissions, _app_definitions.id, _app_costs.id,
_app_costs.cost FROM _app_definitions INNER JOIN _app_costs
ON ( _app_definitions.id = _app_costs.id )'
>>> a = AppDefinitions.objects.select_related().first()
>>> a.id
u'abaqus'
>>> a.cost
Traceback (most recent call last):
File "<console>", line 1, in <module>
AttributeError: 'AppDefinitions' object has no attribute 'cost'
>>> a.appcost
<AppCosts: abaqus,1.50>
>>> a.appcost.cost
Decimal('1.50')
Now there are two problems :
How do I achieve this?
I would be loath to use custom SQL, because that would defeat the purpose of using django's ORM in the first place.
Upvotes: 0
Views: 85
Reputation: 600026
You say you want to use Django's ORM, but then say you want to do something diametrically opposed to that, ie accessing the cost as x.cost
.
Django will not let you do that, since it completely breaks the object model. cost
is an attribute on the AppCosts model, not the Costs one. If it's really bothering you, you could add a property
on Costs which returns self.appcosts.cost
, which will do what you want as long as you don't try to use it in queries.
Upvotes: 1