[Answered ]-Django return specific field from model as foreign key

1👍

“If you’d like to specify a custom primary key, just specify primary_key=True on one of your fields.” https://docs.djangoproject.com/en/1.4/topics/db/models/#automatic-primary-key-fields

So, you can change your class Customer:

class Customer(models.Model):
    name = models.CharField(max_length=64)
    myid = models.CharField(primary_key=True, max_length=64)

1👍

Take a look at serialization with natural keys. You can read the official docs here: https://docs.djangoproject.com/en/1.7/topics/serialization/#natural-keys

It is fairly simple, just add a method to your class:

class Customer(models.Model):
    name = models.CharField(max_length=64)
    myid = models.CharField(max_length=64)

    def natural_key(self):
        return (self.myid, )

And then serialize with use_natural_foreign_keys=True:

def getsetting(request):
    response = serializers.serialize('json', Setting.objects.all(), 
                                     use_natural_foreign_keys=True)
    return HttpResponse(response, content_type='json')

Leave a comment