Django ForeignKey show data from PostgreSQL

蹲街弑〆低调 提交于 2019-12-25 07:25:53

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/36161531/django-foreignkey-show-data-from-postgresql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!