带动态参数的Django模型:如何订购?

时间:2011-08-24 07:55:53

标签: django django-models

我想拥有动态参数,所以我制作了这些模型:

class DynamicObject(models.Model):
    uuid = UUIDField(primary_key=True, editable=False)
    synopsis = models.CharField(max_length=64)
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)

class DynamicObjectParam(models.Model):
    obj = models.ForeignKey(DynamicObject,related_name='params')
    name = models.CharField(max_length=30)
    value = models.CharField(max_length=255)


To list parameters for a particular object, I do :
obj = DynamicObject.objects.get(uuid='xxx')
for p in obj.params:
    print p.name,p.value

要过滤特定参数,我会这样做(这里所有对象都具有参数'server_type',其值为'Sun SF25K':

query_set = DynamicObject.objects.filter(params__name__exact='server_type',params__value__exact='Sun SF25K')

但是如何通过特定的参数名称订购? 例如,我想做一些相当于:

的事情
ordered_query_set = query_set.order_by(params__name='server_name')

当然,这个django语法不存在,所以我该怎么办?

2 个答案:

答案 0 :(得分:1)

我找到了一条路:

ordered_query_set = query_set.extra(select={'param_server_name':'SELECT value FROM app_dynamicobjectparam WHERE dynamicobjectparam.obj_id=app_dynamicobject.uuid AND ci_dynamicobjectparam.name="server_name"'}).order_by('param_server_name')

答案 1 :(得分:0)

你可以通过params__name命令,但是你不能通过这种字符串模式来告诉ORM'的顺序。

在Python上对查询集执行此操作或尝试原始SQL。