【问题标题】:How to retrieve an object with generic relation (ContentType) in Django如何在 Django 中检索具有通用关系(ContentType)的对象
【发布时间】:2021-02-04 07:51:35
【问题描述】:

我在我的 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/', null=True, blank=True)
    is_published = models.BooleanField(default=True)
    slug = models.SlugField(null=False, unique=True)
    price = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True)
    
    tags = GenericRelation(WishListItem, related_query_name='training', null=True, 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 中,我想检索作为WishListItem 对象添加到愿望清单的Training_Lists 对象的price

【问题讨论】:

    标签: python django django-contenttypes


    【解决方案1】:
    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-27
      • 2014-04-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多