Overriding Default Field Names

12 views
Skip to first unread message

rgreene

unread,
May 5, 2014, 7:58:34 PM5/5/14
to django...@googlegroups.com
Good day,

Using a ManyToManyField as in the example below causes django to automatically instantiate a Model called country_region with fields country_id and region_id, which is very cool. But what if the region_country database table (for reasons beyond the scope of this thread) has field names other than country_id and region_id?

Django generates the field names in the many-to-many table based on the model names of the related tables, so the only way I have found to achieve this is to change the two Model names. But that forces me to have model names that I don't want! How can I tell django what field names to use in the automatic many-to-many Model?

I have tried explicitly specifying the many-to-many Model using the through= keyword argument of the ManyToManyField, and this works, but then forms based on the Region Model do not allow saving...

Any advice greatly appreciated,
Randal

class Country(models.Model):
    country_id = models.AutoField(primary_key=True)
    country_name = models.CharField(max_length=200)

    class Meta:
        managed = False
        db_table = 'country'

    def __unicode__(self):
        return '%s' % (self.country_name)

class Region(models.Model):
    region_id = models.AutoField(primary_key=True)
    region_name = models.CharField(max_length=200)
    region = models.ManyToManyField(Country, db_table='region_country')

    class Meta:
        managed = False
        db_table = 'region'
Reply all
Reply to author
Forward
0 new messages