多数据库测试 - 为管理界面创建动态ChoiceField?

时间:2017-11-16 21:46:21

标签: django django-forms

我正在测试多数据库设置,需要在管理界面中填充ChoiceField。我需要通过calendar_app.EventOccurence中的外键,从calendar_app.Event的 title 字段填充的movies.MovieEvent中下拉 movie_title 字段。 在EventOccurence模型中使用外键I can't make movie_title a foreign key,所以我试图拉出记录,然后创建一个元组来填充下拉。

这就是我所拥有的,这会抛出 ValueError,没有足够的值来解包(预期2,得到1):

这些模型将路由到数据库#1

# calendar_app/models.py
class Event(models.Model):
    title = models.CharField(max_length=100)
    tags = models.ManyToManyField(Tag)
    ...

class EventOccurence(models.Model):
    event = models.ForeignKey(Event, related_name='event')
    event_date = models.DateField()
    ...

此模型将路由到数据库#2:

#movies/models.py
class MovieEvent(models.Model):
    movie_title = models.CharField(max_length=80)
    ...

管理

#admin.py
from calendar_app.models import EventOccurrence
...
class MovieEventAdminForm(forms.ModelForm):
    movie_events = EventOccurrence.objects.filter(Q(event__tags__slug__exact='movie')).distinct()
    y = ", (".join(str("'" + x.event.title + "', '" + x.event.title + "')") for x in movie_events)
    movie_choices = str("(" + "(" + y + ")")
    movie_title = forms.ChoiceField(choices=movie_choices)
    class Meta:
        model = MovieEvent
        fields = (
            ...
            'movie_title',
            ... 
        )


class MovieEventAdmin(admin.ModelAdmin):
        form = MovieEventAdminForm

上面抛出了ValueError但是在测试我的元组创建时它返回它就好了。

>>> movie_events = EventOccurrence.objects.filter(Q(event__tags__slug__exact='movie')).distinct()
>>> y = ", (".join(str("'" + x.event.title + "', '" + x.event.title + "')") for x in movie_events)
>>> movie_choices = str("(" + "(" + y + ")")
>>> print(movie_choices)
(('Halloween', 'Halloween'), ('Star Wars', 'Star Wars'), ('Chappie', 'Chappie'))

我做错了什么?

1 个答案:

答案 0 :(得分:0)

我有解决方案。我不知道ModelChoiceField让它变得非常简单:

#admin.py
from calendar_app.models import EventOccurrence
...
class MovieEventAdminForm(forms.ModelForm):
    movie_title = forms.ModelChoiceField(queryset= EventOccurrence.objects.filter(Q(event__tags__slug__exact='movie')).distinct())

    class Meta:
        model = MovieEvent
        fields = (
        ...
        'movie_title',
        ... 
    )


class MovieEventAdmin(admin.ModelAdmin):
    form = MovieEventAdminForm