English 中文(简体)
Django ORM - 更新View 与外钥关系的首字母缩写
原标题:Django ORM - UpdateView form initials with foreignkey relationships

考虑这些假模型:

class City(models.Model):
    name = models.CharField()
    region = models.ForeignKey(Region)

class Region(models.Model):
    name = models.CharField()
    country = models.ForeignKey(Country)

class Country(models.Model):
    name = models.CharField()

和像这样的表格:

class MyForm(forms.Form):
    city = forms.CharField()
    region = forms.CharField()
    country = models.CharField()

我希望我的《更新展望》能显示当前值, 所以我设置了一个类似首字母的首字母:

model_initial = City.objects.filter(id=self.object.id).values()[0]

form = MyForm(initial=model_initial)

有点愚蠢,因为自. object 已经可用,所以我可以手动绘制值图

无论如何,这工作 但关系没有被捕捉, 所以我可以做:

model_initial = City.objects.filter(id=self.object.id).values()[0]
model_initial.update({ region :Somequery,  country :Somequery})

form = MyForm(initial=model_initial)

但那样会非常下流,而且可能不需要。我试图看看哪些选择相关的东西能给我,但是却在那个查询中调用数值来回报额外的字段。

所以,问题:在这种情况下,什么是构建最初判决的好方法?

最佳回答

在Python,"好"通常的意思是"简单易读" 所以我用人性格来表示:

city =  self.object
initial = dict(
  name=city.name, 
  region=city.region.name, 
  country=city.region.country.name
  )

但模范形式或许也是个好解决办法...

问题回答

暂无回答




相关问题
How to get two random records with Django

How do I get two distinct random records using Django? I ve seen questions about how to get one but I need to get two random records and they must differ.

Moving (very old) Zope/Plone Site to Django

I am ask to move data from a (now offline) site driven by Plone to a new Django site. These are the version informations I have: Zope Version (unreleased version, python 2.1.3 ) Python Version 2.1....

Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

Flexible pagination in Django

I d like to implement pagination such that I can allow the user to choose the number of records per page such as 10, 25, 50 etc. How should I go about this? Is there an app I can add onto my project ...

is it convenient to urlencode all next parameters? - django

While writing code, it is pretty common to request a page with an appended "next" query string argument. For instance, in the following template code next points back to the page the user is on: &...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

热门标签