如何在Django中引用与另一个表中的外键匹配的列?

时间:2017-05-05 04:24:50

标签: python django django-models

我是Django的新手。我遇到一个问题,我需要从另一个表中引用既不是主键也不是唯一值的列。这是我的代码:

class Assignment(models.Model):
    assignment_id = models.CharField(primary_key=True, max_length=11)
    investor_id = models.ForeignKey('Investor', to_field='investor_id', models.DO_NOTHING)
    issuer_id = models.ForeignKey('Issuer', to_field='issuer_id', models.DO_NOTHING)
    investor_risk_attitude = models.ForeignKey('Investor', to_field='investor_risk_attitude', models.Do_NOTHING)
    interest_rate = models.FloatField(blank=True, null=True)
    tranche = models.CharField(max_length=20, blank=True, null=True)

    def get_absolute_url(self):
        return reverse ('assignment:index')

    class Meta:
        managed = False
        db_table = 'assignment'

    def __str__(self):
        return self.assignment_id


class Investor(models.Model):
    investor_id = models.CharField(primary_key=True, max_length=11)
    investor_name = models.CharField(max_length=45, blank=True, null=True)
    investor_risk_attitude = models.CharField(max_length=45, blank=True, null=True,db_index=True)

    def get_absolute_url(self):
        return reverse ('investor:index')

    class Meta:
        managed = False
        db_table = 'investor'

    def __str__(self):
        return self.investor_id

    class Issuer(models.Model):
    issuer_id = models.CharField(primary_key=True, max_length=11)
    issuer_name = models.CharField(max_length=45, blank=True, null=True)
    issuer_category = models.CharField(max_length=45, blank=True, null=True)
    total_pool_amount = models.FloatField(blank=True, null=True)
    login_id = models.CharField(max_length=45, blank=True, null=True)
    login_password = models.CharField(max_length=45, blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'issuer'

    def __str__(self):
        return self.issuer_id

在Assignment表中,我需要从Investor表中引用investor_risk_attitude,我已经创建了一个索引,但它不是唯一值。因为investor_id也是Assignment表中的外键,所以我需要risk_attitude来匹配其investor_id。

我还有一个表单允许用户向表中添加新的Assignment记录,代码如下。

class AddAssignment(CreateView):
model = Assignment
fields = ['assignment_id', 'investor', 'issuer', 'investor_risk_attitude', 'interest_rate', 'tranche']

有什么方法可以执行此操作,一旦用户在表单的下拉菜单中选择投资者,就会弹出相应的risk_attitude?非常感谢你?

1 个答案:

答案 0 :(得分:0)

我认为当投资者选择字段发生变化时,您希望从服务器获得实时响应。

您可以在#id_investor_id更改期间调用ajax函数来执行此操作。

在模板中

$(document).on("change", "#id_investor_id", function(){
        var value = $(this).val();
        showDetail(value);
});


function showDetail(value){ 
    if(value !== "" || value !== null){
        var url = "{% url 'get_value' %}";
        $.ajax({
            type : "GET",
            url : url,
            data: { 
                id : value
            } ,
            dataType : 'json',
            success : function(data){
                var status = data['status'];
                alert(status);
            },
        });
    }
}

在views.py

def get_value(request):
    pk = request.GET.get('id')
    instance = Investor.objects.get(pk=pk)
    if instance:
        response_data = {
                "status" : instance.investor_risk_attitude, 
            }
    else:
        response_data = {
            "status" : "false",
            "message" : "value Error"
        }
    return HttpResponse(json.dumps(response_data), content_type='application/javascript')

在urls.py

url(r'^get-value/$', views.get_value, name='get_value'),

如果要从同一个模型中保存两个字段,请添加related_name =" investor_risk_atitude _%(class)s_objects"到你的领域。