【问题标题】:Running a query from Django ModelForm从 Django ModelForm 运行查询
【发布时间】:2013-06-13 17:00:10
【问题描述】:

我有以下现有代码可以使用(我只包括了相关部分)。

models.py

class Customer(models.Model):
    customer_id = models.CharField(primary_key=True, max_length=16)
    account_phone = PhoneNumberField(null=True, blank=True, max_length=255)
    display_phone = PhoneNumberField(null=True, blank=True, max_length=255)
    .
    .
    .

customer.py

@render_to('customer/edit.html')
def edit(request, customer_id):
    customer = Customer.objects.get(customer_id=customer_id)
    if not request.POST:
        return dict(form=CustomerForm(instance=customer))
    submit = request.POST.copy()
    submit['customer_id'] = customer.customer_id
    form = CustomerForm(submit, instance=customer)
    if not form.is_valid():
        return dict(form=form)
    _f = form.save(commit=False)
    _f.save()

class CustomerForm(ModelForm):
    .
    .
    .
    def __init__(self, *args, **kwargs)
        super(CustomerForm, self).__init__(*args, **kwargs)
        .
        .
    class Meta:
        model = Customer

我需要向 CustomerForm 添加一个名为 assigned_numbers 的查询,这将允许我从 account_phonedisplay_phone 获取与 customer_id 关联的电话号码。我被困在如何正确运行查询上,非常感谢任何建议。如果我需要提供更多信息,请告诉我。

【问题讨论】:

    标签: python sql django


    【解决方案1】:

    您的表单是customer 的模型表单,因此它已经包含account_phonedisplay_phone 的字段,除非您以排除它们的方式指定字段。

    如果您需要对它们做一些事情,除了根据您的客户实例开始填充它们的字段之外,您可以访问 form.instance.account_phone 或其他任何东西。

    如果出于某种原因更方便,在您的__init__ 方法中,您可以从kwargs 访问instance 以查找值。

    def __init__(self, *args, **kwargs)
        super(CustomerForm, self).__init__(*args, **kwargs)
        if 'instance' in kwargs:
            self.assigned_numbers = (instance.account_phone, instance.display_phone)
    

    【讨论】:

    • 谢谢。正是我需要的。
    猜你喜欢
    • 2015-03-20
    • 2017-03-25
    • 2020-03-25
    • 2019-08-15
    • 1970-01-01
    • 1970-01-01
    • 2011-03-17
    • 2020-07-06
    • 2014-04-18
    相关资源
    最近更新 更多