0

如果我有很多 Django 模型 - 都具有以下公共字段: -

created_by = models.ForeignKey(User)
modified_by = models.ForeignKey(User)

我想查询所有模型以找出特定用户创建或修改了哪些对象,有没有一种理智的方法可以实现这一目标?

还是我必须退回到做ModelA.objects.filter(created_by=userone) ModelB.objects.filter(created_by=userone)等等?

我应该提到,实际上这些字段位于一个抽象基类中,所有其他模型都从该基类继承它们。但是让我们假装我没有告诉你我刚刚告诉你的关于抽象基类的事情,还有办法做我想做的事吗?

4

2 回答 2

0

You will have to operate on one model at a time. Djano ORM managers internally make use of a class called Queyset which talks with database and this class QuerySet instances have a model attribute on them which is synonymous to a single table. So, they can only talk with one table, though join operations are possible. But for your scenario you will have to make multiple calls to db.

orm is just an abstraction over database, think if you can do this directly with sql.

At sql:

select val from test union select val from test2 union......;

So there will be a lot of unions since you say you have a lot of models so doesn't make much sense to accomplish this with a single db call.

于 2013-04-25T05:24:41.437 回答
0

to expand on what akshar raaj is saying, you can simplify the code by having an array of models.

query_models = [ModelA, ModelB, ModelC, ModelD]
for query_model in query_models:
    results = query_model.objects.filter(created_by=userone)
    if len(results) > 0:
        print '%s has it!!!' % query_model.__name__
于 2013-04-25T05:32:22.950 回答