Attribute name for the secondary key in a template in Django

0

I have a problem with a database imported into Django 1.6.5. In this database the columns follow the pattern: id_city, name, id_state, and so on. But django did not handle it well and I left the class like this:

class City(models.Model):
    id_city = models.IntegerField(primary_key=True)
    state = models.ForeignKey('State', db_column='id_state', blank=False, null=False)
    name = models.CharField(max_length=50, blank=False)
    class Meta:
        managed = False
        db_table = 'city'

To access the id_state field of the table through the template I have two alternatives:

city.state_id
city.state.id_state

In the first alternative it is confusing to work with a name other than the name in the bank, and in the second alternative, an additional query is required to know a single field.

I searched the documentation but did not find a simple way to use the attribute of the way it is in the database, which would look like this:

city.id_state
    
asked by anonymous 04.06.2014 / 02:27

2 answers

1

You do not need to create the id_city field, as Django already creates it for you. Your model gets cleaner and you can access them more easily like this:

city.id
city.state.id

You will not be able to access id_state the way you want it: city.id_state , because the attribute for the State class you have in the City class is state, even your db_column being = 'id_state'.

    
05.06.2014 / 20:28
0

You can use

city.state.pk

Django by default always internally creates a pk attribute that points to the primary key of that model, this can even be used in method get

State.objects.get(pk=123)
    
05.06.2014 / 05:51