質問

I have a ManyToMany relationship with a model City, and it has a field for a Foreign Key with State. I'm trying to get the Django admin field widget to include the State name so that it can autocomplete (because we have thousands of cities in our Django project).

I thought to add the state.name in the City __unicode__, like this:

class State(models.Model):
    name = models.CharField(max_length=100)

class City(models.Model):
    name = models.CharField(max_length=100)
    state = models.ForeignKey(State)
    def __unicode__(self):
        return u'(%s) %d. %s' % (self.state.name, self.id, self.name)

class Person(models.Model):
    cities_lived_in = models.ManyToManyField(City, null=True, blank=True)

But this increases the load time by more than a minute: from 4 seconds to 1.6 minutes.

I'm wondering if there is a less lengthy way to add the state name to Django's manytomany widget. I know I could also alter the modelform, but I think it would produce the same result if not worse, since it would look up all the cities, and then iterate them, and then look up all the related states.

役に立ちましたか?

解決

The issue is that I should be selecting the related models, and in my situation I should be selecting the related models with each query. So instead of doing select_related in the views which I use the City model, I made a custom model manager, like in this SO question: Django: Force select related?

So the City model is as follows now:

class WithState(models.Manager):
    def get_query_set(self):
        return super(WithState, self).get_query_set().select_related('state')        

class City(models.Model):
    name = models.CharField(max_length=100)
    state = models.ForeignKey(State)
    objects = WithState()

    def __unicode__(self):
        return u'(%s) %d. %s' % (self.state.name, self.id, self.name)

Load time is now down to 3 seconds.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top