开发者

Preserving values in model fields when they no longer meet limit_choices_to criteria

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 cus开发者_如何学Ctomizing 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.


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))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜