【发布时间】: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_lable 和 model 参数是什么?
在Users.views.py 中,我想检索作为WishListItem 对象添加到愿望清单的Training_Lists 对象的price。
【问题讨论】:
标签: python django django-contenttypes