Django模型 - 如何添加外键的其他对象

时间:2017-11-03 20:13:54

标签: python django

很难找到如何在表中添加更多来自其他表(外键)的列,见下文:

Models.py:

class Operator(models.Model):
    user_id = models.OneToOneField(User)
    operator_name = models.CharField(max_length=100)
    cnpj = models.CharField(max_length=14)
    def __str__(self):
         return self.operator_name


class Service(models.Model):
    operator_id = models.ForeignKey(Operator, on_delete=models.CASCADE)
    service_type = models.ForeignKey(ServiceType, on_delete=models.CASCADE)
    service_name = models.CharField(max_length=100)
    short_descrip = models.CharField(max_length=100)
    description = models.CharField(max_length=400)
    price = models.IntegerField(default=0)
    address = models.CharField(max_length=200)
    def __str__(self):
        return self.service_name

Views.py

def myagency(request):
    data = serializers.serialize("json", Service.objects.all())
    return HttpResponse(json.dumps(data), content_type="application/json")

在JSON响应中我得到了:

pk: 1
    operator_id: 1
    service_type: 3
    ...

我想收到:

pk: 1
    operator_id: 1
    operator_name: "operator_example"
    service_type: 3
    ...

总结:我想在表格中加入" Service" "主键"和" operator_name"表中的对象"运算符"。

有人知道怎么做吗?

谢谢!

0 个答案:

没有答案