Django:使用一些自定义列序列化queryset并格式化一些字段

时间:2018-08-17 06:04:51

标签: django

我的Django> 2项目中有以下模型:

import Foundation
import Alamofire

class UploadImageController: NSObject {

// MARK: - shared

static let shared  = UploadImageController()

// MARK: - init

let decoder = JSONDecoder()

// MARK: - uploadImageOnly

func uploadImageWith(endUrl: String, photo: UIImage?, parameters: [String : Any]?, headers: HTTPHeaders?, completion: @escaping (_ success: Bool, _ uploadImageResponse: UploadImageResponse?) -> Void ) {

    Alamofire.upload(multipartFormData: { (multipartFormData) in

        if let data = UIImageJPEGRepresentation(photo!, 0.5) {

            multipartFormData.append(data, withName: "invoice", fileName: "invoice.jpeg", mimeType: "invoice/jpeg")
        }

    }, usingThreshold: SessionManager.multipartFormDataEncodingMemoryThreshold, to: endUrl, method: .post, headers: headers) { (result) in

        switch result {

        case .failure(let error):
            print("UploadImageController.requestWith.Alamofire.usingThreshold:", error)
            completion(false, nil)

        case .success(request: let upload, streamingFromDisk: _, streamFileURL: _):

            upload.uploadProgress(closure: { (progress) in
                print("Upload Progress: \(progress.fractionCompleted)")
            })

            upload.responseJSON(completionHandler: { (response) in

                switch response.result {

                case .failure(let error):

                    print("UploadImageController.requestWith.Alamofire.upload.responseJSON:", error)

                    completion(false, nil)

                case .success( _):

                    print("UploadImageController.requestWith.Alamofire.upload.responseJSON Succes")
                    guard let data = response.data else { return }

                    do {

                        let uploadImageResponse = try self.decoder.decode(UploadImageResponse.self, from: data)

                        completion(true, uploadImageResponse)

                    } catch let jsonError {

                        print("Error serializing json.ProfileController.getProfile:", jsonError)
                        completion(false, nil)
                    }
                }
            })
        }
    }
}

// MARK: - uploadImageWithParameters

func uploadImageWithParametersAnd(endUrl: String, photo: UIImage?, parameters: [String : Any]?, headers: HTTPHeaders?, completion: @escaping (_ success: Bool, _ addInvoiceResponse: AddInvoiceResponse?) -> Void ) {

    Alamofire.upload(multipartFormData: { (multipartFormData) in

        if let data = UIImageJPEGRepresentation(photo!, 0.5) {

            multipartFormData.append(data, withName: "invoicePicture", fileName: "invoicePicture.jpeg", mimeType: "invoice/jpeg")
        }

        for (key, value) in parameters! {
            multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: "\(key)")
        }


    }, usingThreshold: SessionManager.multipartFormDataEncodingMemoryThreshold, to: endUrl, method: .post, headers: headers) { (result) in

        switch result {

        case .failure(let error):
            print("UploadImageController.requestWith.Alamofire.usingThreshold:", error)
            completion(false, nil)

        case .success(request: let upload, streamingFromDisk: _, streamFileURL: _):

            upload.uploadProgress(closure: { (progress) in
                print("Upload Progress: \(progress.fractionCompleted)")
            })

            upload.responseJSON(completionHandler: { (response) in

                switch response.result {

                case .failure(let error):

                    print("UploadImageController.requestWith.Alamofire.upload.responseJSON:", error)

                    completion(false, nil)

                case .success( _):

                    print("UploadImageController.requestWith.Alamofire.upload.responseJSON Succes")
                    guard let data = response.data else { return }

                    do {

                        let addInvoiceResponse = try self.decoder.decode(AddInvoiceResponse.self, from: data)

                        completion(true, addInvoiceResponse)

                    } catch let jsonError {

                        print("Error serializing json.ProfileController.getProfile:", jsonError)
                        completion(false, nil)
                    }
                }
            })
        }
    }
 }
}

我想发送帖子列表的JSON响应。并为登录的用户显示每个帖子(无论是否喜欢)。

我希望帖子列表包含请求的布尔值字段“ current_user_like”。用户,

我正在使用以下方式创建帖子的查询集,无论该帖子是否被特定用户喜欢。与https://stackoverflow.com/a/33944811/2897115

相同
class Post(models.Model):
  text = models.TextField()
  date = models.DatetimeField(default=datetime.now, blank=True)

class Like(models.Model):
  post = models.ForeignKey(Post)
  user = models.ForeignKey(User, related_name="current_user_likes")

我期望使用以下JSON:

posts = Post.objects.all().prefetch_related(
    Prefetch('current_user_likes', queryset=Like.objects.filter(user=request.user))
)

因此,希望Json具有格式化的日期,并且还要添加“ current_user_likes”字段。

操作方法

1 个答案:

答案 0 :(得分:1)

对于日期格式,您可以直接使用Exists并使用一些数据库函数来转换格式。

对于类似的建议,我建议使用annotate()并放入qs = Post.objects.all() sub = Like.objects.filter(post__id=OuterRef('pk'), user=request.user) values = qs.annotate( date=Func(F('date'), function='db_specific_date_formatting_func'), current_user_like=Exists(sub) ).values('text, 'date', 'current_user_like')

抱歉,我无法检查语法,但这应该可以正常工作

{{student.fullName}}