如何将外键id转换为值 - Django

时间:2014-10-23 19:06:14

标签: python ajax json django http

我在Django的Models文件中定义了以下models.py

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', ) 

因此群集的HadoopDistributor就像Cloudera一样。然后,在我的views.py上,我查询特定用户创建的所有群集的列表:

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")

现在,当我做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
  },

但我希望价值为:

{
  "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
  },

执行此操作的简单方法是使用外键替换所有元素的名称,然后返回,但我想知道是否有一种简单的方法可以实现此目的。我读了__unicode__模型中Django的一些内容,但我无法理解它是如何帮助我实现我想要的。有什么帮助吗?

1 个答案:

答案 0 :(得分:1)

答案是在natural_key(self)

中实施方法HadoopDistributor

所以

def natural_key(self):
  return self.name

__unicode____str__的旁注上,您应该真正实现:

 def __unicode__(self):
   return self.name

 def __str__(self):
   return unicode(self).encode('utf-8')