Reputation: 10961
I defined the following Models
in my models.py
file in Django:
class HadoopDistributor(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class Cluster(models.Model):
size = models.IntegerField(default=0)
name = models.CharField(max_length=300, default="")
hadoop_dist = models.ForeignKey(HadoopDistributor)
hadoop_version = models.ForeignKey(HadoopVersion)
dgsecure = models.ForeignKey(DgSecure)
user = models.ForeignKey(User)
datafiles = models.ManyToManyField(Data)
created = models.DateTimeField(default=None)
deleted = models.DateTimeField(default=None, blank=True)
FAILED = 'FL'
RUNNING = 'RN'
SUCCESS = 'SC'
DESTROY = 'DS'
STATUS = (
(FAILED, 'FAILED'),
(RUNNING, 'RUNNING'),
(SUCCESS, 'SUCCESS'),
(DESTROY, 'DESTROY')
)
status = models.CharField(max_length=2,
choices=STATUS,
default=FAILED)
def __str__(self):
return self.name
def __unicode__(self):
pass
class Meta:
ordering = ('hadoop_version', )
so a cluster has a HadoopDistributor
, like Cloudera
. Then, on my views.py
, I query the list of all the clusters created by a particular user:
def get_cluster_list(request):
clusters = Cluster.objects.filter(user=request.user)
cluster_obj = serializers.serialize('json',
clusters,
indent=2,
use_natural_foreign_keys=True,
use_natural_primary_keys=True)
return HttpResponse(cluster_obj, content_type="application/json")
Now, when I do a HTTP
`GET:
{
"fields": {
"status": "FL",
"hadoop_dist": 1,
"dgsecure": 1,
"name": "",
"created": "2014-10-22T22:58:41Z",
"deleted": "2014-10-22T22:58:41Z",
"user": [
"philippe"
],
"datafiles": [],
"hadoop_version": 2,
"size": 2
},
but I expect the value to be:
{
"fields": {
"status": "FL",
"hadoop_dist": "Cloudera",
"dgsecure": 1,
"name": "",
"created": "2014-10-22T22:58:41Z",
"deleted": "2014-10-22T22:58:41Z",
"user": [
"philippe"
],
"datafiles": [],
"hadoop_version": 2,
"size": 2
},
The trivial way to do this is to replace all the elements using the foreign key by it's name, and then return, but I wonder if there's a easy way to accomplish this. I read a little bit about the __unicode__
in the Django
model, but I couldn't understand how that could help me achieve what I want. Any help?
Upvotes: 0
Views: 1421
Reputation:
The answer is to implement the method natural_key(self)
in HadoopDistributor
So
def natural_key(self):
return self.name
On a side note for __unicode__
and __str__
you should really implement:
def __unicode__(self):
return self.name
def __str__(self):
return unicode(self).encode('utf-8')
Upvotes: 1