Django使用自定义管理器从多态模型获取记录

时间:2018-12-11 09:18:53

标签: python django django-orm

models.py

# My Model
class MyModel(BaseModel):
    somefield1 = models.CharField(max_length=100)
    somefield1 = models.CharField(max_length=100)
    my_records = MyModelManager()

    class Meta:
        db_table = 'my_table'

# My Polymorphic Model
class PolModel(BaseModel):
    source_id = models.IntegerField()
    source_type = models.CharField()

    class Meta:
        db_table = 'pol_model'

managers.py

# Display Actives QuerySet
class MyModelManager(models.Manager):

    def __init__(self, *args, **kwargs):
        super(MyModelManager, self).__init__(*args, **kwargs)

    def get_queryset(self):
        my_queryset = super(MyModelManager, self).get_queryset()



        return my_queryset.filter(deleted_at=None).extra(
                select={"inner join pol_model on my_table.id = 
                         pol_model.source_id"
                        "WHERE pol_model.type = 'MyExample'"}
            )

每次我选择MyModel实例时,我都想从多态模型中获取与实例相关的记录。我尝试过此解决方案在queryset中添加了额外的内部联接,但是id没有作用

0 个答案:

没有答案