Skip to content

Instantly share code, notes, and snippets.

@marioidival
Last active December 20, 2015 15:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marioidival/6156074 to your computer and use it in GitHub Desktop.
Save marioidival/6156074 to your computer and use it in GitHub Desktop.
How to serializer FK :)
from django.db import models
class PersonManager(models.Manager):
def get_by_natural_key(self, first_name, last_name):
return self.get(first_name=first_name, last_name=last_name)
class Person(models.Model):
objects = PersonManager()
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
birthdate = models.DateField()
def natural_key(self):
return (self.first_name, self.last_name)
class Book(models.Model):
name = models.CharField(max_length=100)
author = models.ForeignKey(Person)
#In views
data = serializers.serialize('json', list(Book.objects.all()), use_natural_keys=True)
#before:
{
"pk": 1,
"model": "store.book",
"fields": {
"name": "Mostly Harmless",
"author": 42
}
}
# AFTER: return this wonderful JSON
{
"pk": 1,
"model": "store.book",
"fields": {
"name": "Mostly Harmless",
"author": ["Douglas", "Adams"]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment