Django - Get ContentType model by model name (Generic Relations)

前端 未结 1 1351
小鲜肉
小鲜肉 2021-02-04 03:02

I\'m thinking about this for a while now,

I\'m creating a chat application, in chat.models a class Room is specified, however, a Room can be related to anything in my pr

1条回答
  •  不知归路
    2021-02-04 03:06

    http://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#methods-on-contenttype-instances

    user_type = ContentType.objects.get(app_label="auth", model="user")
    user_type = ContentType.objects.get(model="user")
    # but this can throw an error if you have 2 models with the same name.
    

    Very similar to django's get_model

    from django.db.models import get_model
    user_model = get_model('auth', 'user')
    

    To use your example exactly:

    ctype = ContentType.objects.get(model='user')
    related_to_user = Room.objects.filter(content_type=ctype)
    

    0 讨论(0)
提交回复
热议问题