Attribute name referring to secondary key in a model in Django

Asked

Viewed 119 times

0

I have a problem with an imported database for Django 1.6.5. In this database the columns follow the pattern: id_city, name, id_state and etc. However, Django did not handle it well leaving 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 model I have two alternatives:

  1. city.state_id
  2. 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 it is necessary an additional query to know a single field.

I searched the documentation but I couldn’t find a simple way to use the attribute the way it is in the bank, which would be like this:

city.id_state
  • What you want to understand is the concept of relationship between one table and the other ? relatedly 1 to 1 ,1 to many ? would be what you want ?

2 answers

0

You can use

city.state.pk

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

State.objects.get(pk=123)
  • My problem is with secondary key and city.state.pk equals city.state.id_state as far as I know. So one more query is required.

0

You don’t need to create the id_city field. Django already creates it for you. Your model gets cleaner and you can access it more easily like this:

city.id
city.state.id

You won’t be able to access the id_state the way you want: city.id_state, because the attribute referring to the State class you have in the City class is state, even though your db_column is ='id_state'.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.