I have several basic models with several control fields. Among them, the location fields are from lat, lon, accuracy, provider and client time. Most of my writable models (and therefore resources) inherit from this base model.
I am trying to make DRF serialize the fields associated with a location in a nested "location" field. For example,
{ "id": 1, "name": "Some name", "location": { "lat": 35.234234, "lon": 35.234234, "provider": "network", "accuracy": 9.4, } }
It is important to remember that these fields are regular (flat) fields of the base model.
I researched and found some options
Create a custom field and, overriding "get_attribute", create a subview. I do not like this solution because I lose some of the benefits of the model serializer, such as validation.
Create a sub resource called Location. I think I could make it work by adding a property with the same name on the model, but again, no checks.
So my question is: What is the best way to nest (or group) multiple fields in a DRF serializer?
DRF 3.0.0, Django 1.7
EDIT:
Building on top of @Tom Christie answer, here's what I came up with (simplified)
# models.py class BaseModel(models.Model): id = models.AutoField(primary_key=True) lat = models.FloatField(blank=True, null=True) lon = models.FloatField(blank=True, null=True) location_time = models.DateTimeField(blank=True, null=True) location_accuracy = models.FloatField(blank=True, null=True) location_provider = models.CharField(max_length=50, blank=True, null=True) @property def location(self): return { 'lat': self.lat, 'lon': self.lon, 'location_time': self.location_time, 'location_accuracy': self.location_accuracy, 'location_provider': self.location_provider } class ChildModel(BaseModel): name = models.CharField(max_lengtg=10)
I tested with a valid / invalid message / patch and it worked perfectly.
Thanks.
django django-rest-framework
haki
source share