查询表格中的模型数据以清理DB

时间:2018-02-22 06:26:41

标签: python django django-models django-forms

所以我有forms.py,如下所示:

from django import forms
from .models import SipExtension
from xmpp.models import xmpp_buddy_groups

class ExtensionForm(forms.Form):
    xmpp_buddy_groups_choices = xmpp_buddy_groups.objects.values_list('group_name',flat=True)


    boolean_choices=(('Yes','Yes'),('No','No'))
    sip_extension = forms.IntegerField(min_value=0,max_value=100000)
    sip_secret = forms.CharField(required=True,max_length=32)
    commlink_push = forms.ChoiceField(choices=boolean_choices,widget=forms.CheckboxSelectMultiple,required=True)
    real_name = forms.CharField(required=True,max_length=32)
    xmpp = forms.ChoiceField(choices=boolean_choices,widget=forms.CheckboxSelectMultiple,required=True)
    xmpp_username = forms.CharField(required = True,min_length=5)
    xmpp_password = forms.CharField(max_length=32, widget=forms.PasswordInput)
    xmpp_buddy_groups_names = forms.MultipleChoiceField(choices=xmpp_buddy_groups_choices,widget=forms.CheckboxSelectMultiple,required=False)

如果我的数据库已经由之前的迁移创建,那么它可以正常工作。但是当我的数据库空白时,我遇到了问题。为了测试,我删除了所有表,然后运行make migrations并得到以下错误:

django.db.utils.ProgrammingError: relation "extensions_sipextension" does not exist
LINE 1: ...p_buddy_groups_names"."xmpp_buddy_groups_id" FROM "extension...

当我需要在全新系统上部署时,我在空白数据库上处理此问题时遇到问题。我可以通过注释正在执行需要此表单的视图的URL来处理它,但这是一个糟糕的临时工作。如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

我认为问题在于表单中的xmpp_buddy_groups_choices属性。在项目加载时评估查询集。因此,当您使用./manage.py makemigrations时,xmpp_buddy_groups_choices尝试评估查询集,但由于数据库中没有表而失败。尝试将选项包装在函数中,并在choices参数中传递该函数。

您的choices必须是元组列表(包含2个元素),但xmpp_buddy_groups_choices是字符串列表。

示例代码:

class ExtensionForm(forms.Form):
    @staticmethod
    def get_group_choices():
        xmpp_buddy_groups_choices = xmpp_buddy_groups.objects.values_list('group_name',flat=True)
        return xmpp_buddy_groups_choices


    boolean_choices=(('Yes','Yes'),('No','No'))
    sip_extension = forms.IntegerField(min_value=0,max_value=100000)
    sip_secret = forms.CharField(required=True,max_length=32)
    commlink_push = forms.ChoiceField(choices=boolean_choices,widget=forms.CheckboxSelectMultiple,required=True)
    real_name = forms.CharField(required=True,max_length=32)
    xmpp = forms.ChoiceField(choices=boolean_choices,widget=forms.CheckboxSelectMultiple,required=True)
    xmpp_username = forms.CharField(required = True,min_length=5)
    xmpp_password = forms.CharField(max_length=32, widget=forms.PasswordInput)
    xmpp_buddy_groups_names = forms.MultipleChoiceField(choices=ExtensionForm.get_group_choices,widget=forms.CheckboxSelectMultiple,required=False)