0

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 :

  • The query pulls in id twice from both fields (not a big deal because this table wont have more than a few hundred entries at most, but still, I want it to be right)
  • I have to access cost as x.appcost.cost, rather than simply x.cost

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.