简体   繁体   中英

How to refer a column that matches a foreign key in another table in Django?

I am very new to Django. I run into a problem where I need to refer a column that is neither a primary key nor unique value from another table. Here is my code:

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

In Assignment table, I need to refer investor_risk_attitude from the Investor table, which I have made an index, but it is not a unique value. Because investor_id is also a foreign key in Assignment table, so I need the risk_attitude to match with its investor_id here.

I also have a form that allows users to add new Assignment record to the table, the code is as below.

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

Is there any way I can execute this in a way where the corresponding risk_attitude would pop up once the user chooses the investor in the drop-down menu in the form? Thank you very much?

I think you want a real time response from server when the investor choice field changes.

You can do this by calling an ajax function during the #id_investor_id change.

In template

$(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);
            },
        });
    }
}

In 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')

In urls.py

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

If you want to save two field from same Model then add related_name="investor_risk_atitude_%(class)s_objects" to your field.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM