Django ForeignKey显示PostgreSQL的数据 [英] Django ForeignKey show data from PostgreSQL
问题描述
所以,现在在模型中,我创建了(基于表单)变量,名为 type = models.ForeignKey('TBL1',db_column ='type',related_name ='type'),它返回给我Django对象模型ForeignKey,我猜可以。我想以选择的形式显示,我不知道如何从 TBL1 获取数据。有没有办法这样做,因为我已经搜索了2-3天,并尝试其他选项,但是他们没有做到这一点?我已经发现,例如
STATUS_CHOICES =(
('new',_('New')),
$($ purchase $)
status = models.CharField(max_length = 200,default ='new',choices = STATUS_CHOICES)
在表单中显示选择:
PS
Django版本是1.5.4和Python 2.7,我从来没有在Django或PostgreSQL中工作,所以任何帮助将不胜感激。感谢
所以在做了一些更多的研究后,我偶然发现了链接,其中很好地解释了如何在admin.py中编辑内联选项,尽管我正在等待时间尝试添加来自model.py的数据
class FooForm(forms.ModelForm):
class Meta:
model = Foo
def __init __(self,* args,** kwargs):
super(FooForm,self).__ init __(* args,** kwargs)
current_state = self.instance.state
...根据当前状态构造available_choices ...
self.fields ['state']。choices = available_choices
它的工作就像我希望工作:)
所以感谢很多人尝试帮助,我不是python / django dev,所以这一切都不符合我的语法:)
最好的所有
i have a db in PostgreSQL which is connecting 2 different tables lets call them TBL1 ( TBL1 is a table for all types ) and TBL2( TBL2 is a table for e.g. cars ), TBL1 and TBL2 have a same column named type, so i have created the foreign key between them. Because i'm not sure if that has anything to do with Django...
So, now in model, i have created ( based on the form ) variable called type = models.ForeignKey('TBL1', db_column='type', related_name='type') and it's returning to me Django object model ForeignKey, which i guess is ok. I would like to show that in a form like select and i don't know how to get the data from TBL1. Is there any way to do this, because i have searched for 2-3 days and trying other options, but non of them did the trick ? I have find out that e.g.
STATUS_CHOICES = (
('new', _('New')),
('purchased', _('Purchased'))
)
status = models.CharField(max_length=200, default='new', choices=STATUS_CHOICES)
Is showing the select in form :
P.S.
Django version is 1.5.4 and Python 2.7 , i have never worked in Django or PostgreSQL, so any help would be appreciated. Regards
So after doing some more research , i have stumbled upon link , where it's nicely explained how you can edit the choices "inline" inside admin.py , although i was waisting time trying to add the data from model.py
class FooForm(forms.ModelForm):
class Meta:
model = Foo
def __init__(self, *args, **kwargs):
super(FooForm, self).__init__(*args, **kwargs)
current_state = self.instance.state
...construct available_choices based on current state...
self.fields['state'].choices = available_choices
And it worked just as i hoped to work :)
So thanks a lot guys for trying to help, i'm not python/django dev, so this all are not similar syntax to me at all :)
Best all
这篇关于Django ForeignKey显示PostgreSQL的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!