I'm trying to figure out the best way to serialize a nested relationship for my Angular.js app.
class File(models.Model):
"""
A file upload
"""
name = models.CharField(max_length=255, help_text="Display name for the file. Defaults to the file name.")
file = models.FileField(upload_to="uploads")
file_type = models.CharField(max_length=50)
user = models.ForeignKey(settings.AUTH_USER_MODEL)
class Entry(models.Model):
"""
An entry will have 1 of the following fields: file, text, url
"""
created_for = models.ForeignKey(settings.AUTH_USER_MODEL)
created_by = models.ForeignKey(settings.AUTH_USER_MODEL)
entry_type = models.ForeignKey('EntryType')
file = models.ForeignKey('files.File', null=True, blank=True)
text = models.TextField(blank=True)
url = models.CharField(max_length=255, blank=True)
Basically, I want to create new Entries for existing Files using the file id (
like a PrimaryKeyRelatedField), and get
Entries with all the File fields included with the response, not just
the id (
like the nested relationship example).
I'm currently using the default ModelSerializer for the Entries. When I create a new entry with a file attachment, I set the pk to an existing file, and when I get entries, it returns the pk for the file.
{
"id": 47,
"created_for": 2,
"created_by": 1,
"entry_type": "document",
"file": 18,
"text": "",
"url": "",
...
},
However, when I get Entries, I want to pass the fields of the file, not just the id (
like the nested relationship example), like this:
{
"id": 47,
"created_for": 2,
"created_by": 1,
"entry_type": "document",
"file": {
"id": 18,
"name": "My document",
"file": "path/to/my_document.doc"
"file_type": "application/msword",
"user": 1
},
"text": "",
"url": "",
...
},
So, how can I implement this nested serializer functionality for get requests, but still use the file pk when creating new Entries? Or, perhaps there's a different implementation I should be pursuing altogether.
I would appreciate any direction you can provide. Thanks!