有没有办法在序列化Django模型类时将任何@property定义传递给json序列化程序?
例:
class FooBar(object.Model)
name = models.CharField(...)
@property
def foo(self):
return "My name is %s" %self.name
Run Code Online (Sandbox Code Playgroud)
想序列化为:
[{
'name' : 'Test User',
'foo' : 'My name is Test User',
},]
Run Code Online (Sandbox Code Playgroud) 我们假设我创建了两个模型:
class Car(models.Model):
name = models.CharField(max_length=50)
size = models.IntegerField()
class Manufacturer(models.Model):
name = models.CharField(max_length=50)
country = models.CharField(max_length=50)
car = models.ManyToManyField(Car)
Run Code Online (Sandbox Code Playgroud)
我在两个模型中添加了条目,然后我意识到每辆车只与一个独特的制造商有关.所以,我应该将ManyToManyField转换为ForeignKey:
class Car(models.Model):
name = models.CharField(max_length=50)
size = models.IntegerField()
manufacturer = models.ForeignKey(Manufacturer)
class Manufacturer(models.Model):
name = models.CharField(max_length=50)
country = models.CharField(max_length=50)
Run Code Online (Sandbox Code Playgroud)
如何在不丢失参赛作品的情况下做到这一点?我试着查看南方文档,但我没有找到这种转换方式......
操作django.db.models.Q对象的中性元素是什么|?我想生成一个带有函数的过滤器:
MyModel.objects.filter(myfunc(args)) where myfunc should give something like: "Q(foo) | Q(bar) | ... | False"
Run Code Online (Sandbox Code Playgroud)
但我不知道什么是False对Q的对象.同样,我需要中性元素进行&操作(True)...
以下是此类功能的示例:
# Models
class MyModel(models.Model):
myfield1 = models.CharField(max_length=30)
myfield2 = models.CharField(max_length=30)
# Views
class MyView(views.View):
model = MyModel
def get_queryset(self):
def myfunc(query_object_list, param):
myfuncr = lambda l: ((myfuncr(l[1:]) | Q(**{ param: l[0] })) if l else Q(False)) # "Q(False)" would be the neutral element of operation "|" for Q objects
return myfuncr(query_object_list) …Run Code Online (Sandbox Code Playgroud)