如何将url中的初始数据传递给外键字段?

时间:2014-08-02 16:35:42

标签: django django-models django-forms

我正在使用ModelForm。我知道如何传递初始数据,如: “domain.com/?field=value” 如果字段是CharField或类似的东西,但如果字段是ForeignKey,如何传递初始数据? “domain.com/?field__foreign=value”;)无效。

1 个答案:

答案 0 :(得分:1)

您在网址?之后放置的内容不是字段,它们是可选参数。然后,您可以在视图中使用它们,并根据需要将它们作为字段进行威胁。

示例:domain.com/?field=myValue

def yourView(request, field=""): #The field has an ampty string as default if not provided in the URL
  #Now we will retrieve the objects where the field "yourField" has the value given in the url (or empty string if none)
  #In the case of this example, field = myValue
  yourObjects = yourModel.filter(yourField = field)
  #Do anything else you want to do in your view
相关问题