[Answer]-How can implement foreign key in admin and model

1👍

Add primary_key parameter to Sttlmnt_typ_Master.stt_typ_code and then change DLVR.sett_type to foreign key:

class Sttlmnt_typ_Master(models.Model): 
    stt_typ_code = models.CharField(max_length=10, primary_key=True)
    stt_typ_name =  models.CharField(max_length=35)

    def __unicode__(self):
        return self.stt_typ_name

class DLVR(models.Model):
      sett_type = models.ForeignKey(Sttlmnt_typ_Master)
      sett_num = models.CharField(max_length=7)

Admin will be as simple as:

class DLVRAdmin(admin.ModelAdmin):
    list_display = ['sett_type', 'sett_num']
    search_fields=['sett_num','sett_type__stt_typ_name']

To set raw data to DLVR.sett_type (for example while import from CSV) add _id to field name:

DLVR.objects.create(sett_type_id='O', sett_num='2014232')

Leave a comment