在Django模型中具有完整的字段对象而不是它的ID

时间:2019-08-16 17:57:47

标签: django django-models django-admin

使用这两个模型TblPhoto

class TblPhoto(models.Model):
    #path = models.CharField(max_length=256)
    type = models.ForeignKey('TblPhotoTypes', models.DO_NOTHING, blank=True, null=True)
    path = models.ImageField(upload_to='images')

    def __str__(self):
        return str(self.id)

    class Meta:
        managed = False
        db_table = 'tbl_photo'
        verbose_name = "Photo"
        verbose_name_plural = "Photos"

和TblCustomer

class TblCustomer(models.Model):
    name = models.CharField(max_length=32)
    email = models.CharField(max_length=32)
    password = models.CharField(max_length=32)
    token = models.CharField(max_length=64, blank=True, null=True)
    firebase_token = models.CharField(max_length=64, blank=True, null=True)
    registration_date = models.IntegerField(blank=True, null=True)
    last_login_date = models.IntegerField(blank=True, null=True)
    about = models.TextField(max_length=128, blank=True, null=True)
    active = models.BooleanField(blank=True, null=True)
    photo = models.ForeignKey(TblPhoto, models.DO_NOTHING)

    def __str__(self):
        return str(self.id)+' : '+self.name

    class Meta:
        managed = False
        db_table = 'tbl_customer'
        verbose_name = "Customer"
        verbose_name_plural = "Customers"

api响应是...

{
    "response_status": {
        "code": 200,
        "internalMessage": "",
        "message": ""
    },
    "user": {
        "id": 1,
        "name": "deya",
        "email": "gmail@gmail.com",
        "password": "",
        "token": null,
        "firebase_token": null,
        "registration_date": null,
        "last_login_date": null,
        "about": "hello, i'm Deya !",
        "active": true,
        "photo_id": 4
    }
}

注意字段photo_id,如何更改TblCustomer模型以显示照片对象而不是照片ID?

  

免责声明:我可以轻松地在模型外执行此操作,但我希望它可以在   模型类。

这就是我现在的方法...获取附加的photo_url密钥,但我想从模型中进行此操作。...

class CustomerProfileView(BaseView):
    def post(self, request, format=None):
        requestBody = json.loads(request.body)
        id = requestBody["id"]
        try:
            user = TblCustomer.objects.values().get(id=id)
            photo = TblPhoto.objects.values().get(id=user["photo_id"])
            user["photo_url"] = request.scheme+"://"+request.get_host()+"/media/"+photo["path"]
            self.responseDict["user"] = user
        except Exception as e:
            return Helpers().statusCode(404,e)
        return JsonResponse(self.responseDict)

0 个答案:

没有答案