微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在 Django 中检索具有泛型关系 (ContentType) 的对象

如何解决如何在 Django 中检索具有泛型关系 (ContentType) 的对象

我在 django 3.1 项目中使用 ContentType 来实现一个愿望清单。

这是我的models.py

# Users.models.py
class WishListItem(models.Model):
    owner = models.ForeignKey(User,on_delete=models.CASCADE)
    
    title = models.CharField(max_length=50,null=True,blank=True)
    count = models.IntegerField(null=True,blank=True)
    price = models.DecimalField(max_digits=10,decimal_places=2,blank=True,null=True)
    
    content_type = models.ForeignKey(ContentType,on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type','object_id')

我在其他模型(来自其他应用)中声明了 genericRelation

例如:

another_app.models.py

# Support.models.py
class Training_Lists(models.Model):

    title = models.CharField(max_length=50,unique=True)
    cover = models.ImageField(upload_to='photos/support/tranings/',blank=True)
    is_published = models.BooleanField(default=True)
    slug = models.SlugField(null=False,unique=True)
    price = models.DecimalField(max_digits=10,null=True)
    
    tags = GenericRelation(WishListItem,related_query_name='training',blank=True)

在我的场景中,我想检索一个 training 对象以获得它的 price

基于 ContentType.get_object_for_this_type(**kwargs) 的 Django 文档,我应该检索我正在寻找的模型类型,然后使用 get_object_for_this_type 获取对象。在文档中,它说:

from django.contrib.contenttypes.models import ContentType
user_type = ContentType.objects.get(app_label='auth',model='user')  # <= here is my question
user_type
<ContentType: user>

user_type.get_object_for_this_type(username='Guido')
<User: Guido>

这是我的问题:什么是 app_lablemodel 参数?

Users.views.py 中,我想检索作为 price 对象添加到心愿单的 Training_Lists 对象的 WishListItem

解决方法

from django.contrib.contenttypes.models import ContentType
user_type = ContentType.objects.get_for_model(User)  # <= here is your answer
user_type
<ContentType: user>

user_type.get_object_for_this_type(username='Guido')
<User: Guido>

参考:ContentType get_for_model

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。