如何将django Model对象转换为包含其所有字段的dict ?理想情况下,所有内容都包含外键和带有editable = False的字段.
让我详细说明一下.假设我有一个类似以下的django模型:
from django.db import models
class OtherModel(models.Model): pass
class SomeModel(models.Model):
    normal_value = models.IntegerField()
    readonly_value = models.IntegerField(editable=False)
    auto_now_add = models.DateTimeField(auto_now_add=True)
    foreign_key = models.ForeignKey(OtherModel, related_name="ref1")
    many_to_many = models.ManyToManyField(OtherModel, related_name="ref2")
在终端中,我做了以下事情:
other_model = OtherModel()
other_model.save()
instance = SomeModel()
instance.normal_value = 1
instance.readonly_value = 2
instance.foreign_key = other_model
instance.save()
instance.many_to_many.add(other_model)
instance.save()
我想将其转换为以下字典:
{'auto_now_add': datetime.datetime(2015, 3, 16, 21, 34, 14, 926738, tzinfo=<UTC>),
 'foreign_key': 1,
 'id': 1,
 'many_to_many': [1],
 'normal_value': 1,
 'readonly_value': 2}
回答不满意的问题:
我想在Django中序列化单个模型的值.因为我想使用get(),values()不可用.但是,我在Google网上论坛上读到您可以使用以下内容访问这些值__dict__.
from django.http import HttpResponse, Http404
import json
from customer.models import Customer
def single(request, id):
    try:
        model = Customer.objects.get(id=id, user=1)
    except Customer.DoesNotExist:
        raise Http404
    values = model.__dict__
    print(values)
    string = json.dumps(values)
    return HttpResponse(string, content_type='application/json')
print语句输出.
{'_state': <django.db.models.base.ModelState object at 0x0000000005556EF0>, 'web
site': 'http://example.com/', 'name': 'Company Name', 'id': 1, 'logo': '', 'use
r_id': 1, 'address3': 'City', 'notes': '', 'address2': 'Street 123', 'address1': 'Company Name', 'ustid': 'AB123456789', 'fullname': 'Full Name Of Company Inc.', 'mail': …我想以json格式序列化自定义对象,其中entryData是我的域对象的列表.像这样的东西:
{
    "total":2,
    "current":1,
    "entryData":[
        {
            "id":1,
            "version":0,
            "name":"Default Station"
        },
        {
            "id":2,
            "version":3,
            "name":"Default Station 1"
        }
    ]
}
这是我在我的一次尝试中获得json输出所做的事情:
def ground_station_listgrid(request):
    entryData = serializers.serialize("json", GroundStation.objects.all())
    response_data = {}
    response_data['totalPages'] = 2
    response_data['currentPage'] = 1
    response_data['entryData'] = entryData
    return HttpResponse(json.dumps(response_data),mimetype='application/json')
但结果是entryData被评估为一个字符串,引号被转义:
{
"totalPages": 1, 
"currentPage": 1, 
"entryData": "[{\"pk\": 1, \"model\": \"satview.groundstation\", ....
我也尝试过这样的事情:
def ground_station_listgrid(request):
    response_data = {}
    response_data['totalPages'] = 1
    response_data['currentPage'] = 1
    response_data['entryData'] = GroundStation.objects.all()
    return HttpResponse(json.dumps(response_data),mimetype='application/json')
但是我得到了这个例外: [<GroundStation: nome>, <GroundStation: nome>, <GroundStation: nome>] is not JSON …
是否可以使用具有相同属性的模型的另一个对象来创建对象?
就我而言,我有两个模型 -TemporaryJob和Job. 在TemporaryJob当用户填写表单创建。接下来要做的就是确认。如果他确认TemporaryJob,则该对象应转换为常规Job对象。
class Job(models.Model):
    attributes
    methods
class TemporaryJob(Job):
    pass
我试过了,Job.objects.create(temporary_job_instance)但它不起作用。