0

I'm wondering if there is a convention for naming a foreign key field in Django that is mapped to another field with to_field. For example, should the Django field name be the model name and the database field name be the column name or is that confusing?

class Stations(models.Model):
    name = models.CharField()
    observations = models.ForeignKey(Observations, 
                                     to_field='zone_code'
                                     db_column='zone_code')

class Observations(models.Model):
    zone_code = models.IntegerField(unique=True)
    metric_a = models.IntegerField()
    metric_a = models.IntegerField()

It doesn't really make sense to have this:

class Stations(models.Model):
    name = models.CharField()
    observations = models.ForeignKey(Observations, 
                                     to_field='zone_code')

class Observations(models.Model):
    zone_code = models.IntegerField(unique=True)
    metric_a = models.IntegerField()
    metric_a = models.IntegerField()

nor this

class Stations(models.Model):
    name = models.CharField()
    zone_code = models.ForeignKey(Observations, 
                                     to_field='zone_code')

class Observations(models.Model):
    zone_code = models.IntegerField(unique=True)
    metric_a = models.IntegerField()
    metric_a = models.IntegerField()

because then you end up with observations_id or zone_code_id when the column in the database is actually the zone_code. Anyone have this issue before?

moku
  • 4,099
  • 5
  • 30
  • 52
  • What's the problem with your first version? You are mapping to a `Oberservations` object so naming it `observations` is clear and concise. `to_field` merely describes which field you use for identifying the related object but that's a different story. It's still a `Observations` object. – a_guest May 05 '17 at 20:43
  • Just trying to verify the convention. Thanks for your input. – moku May 05 '17 at 21:02
  • Possible duplicate of [Include other field as choices to foreign key, Django](http://stackoverflow.com/questions/43906504/include-other-field-as-choices-to-foreign-key-django) – e4c5 May 16 '17 at 03:45

0 Answers0