views:

18

answers:

1

I have an Article model that has a foreign key relationship with Author that needs to use a limit_choices_to because I have over 2,000 possible authors in the database. The problem is that when these authors no longer meet the limit_choices_to criteria (e.g. they become inactive), they disappear from the author field when I edit old articles and therefore I can't save them as the author on those old articles.

How do I use limit_choices_to while preserving the value in the field, even if it would otherwise be excluded by limit_choices_to?

I have tried customizing save() and init, rewriting the original value using clean(), and even tried to use a custom admin form without success. Surely someone has run into this dilemma and I'm probably missing something easy, but I'm stumped.

+1  A: 

I think the way to do this would be in the init of a custom form, where you could dynamically modify the choices of the Author field to include the current author. Something like (untested):

def __init__(self, *args, **kwargs):
    super(MyForm, self).__init__(*args, **kwargs)
    current_author_id = self.instance.author_id
    self.fields['author'].queryset = Author.objects.filter(Q(is_active=True) | 
                                                         Q(pk=current_author_id))
Daniel Roseman
Works perfectly! The only tweak I had to make was to change current_author_id = self.instance.author_id to: current_author_id = self.instance.author_id.id. You have no idea how grateful I am for your answer. Thank you!
Jamie