简体   繁体   English

使用 if 语句检查内容类型以确定要执行的操作

[英]Check content type with if statement to determine what to do

I have django model with a generic relation associated.我有一个关联通用关系的 django 模型。

class SectionLine(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    ...
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.UUIDField( default=uuid.uuid4, editable=True)
    content_object = GenericForeignKey('content_type', 'object_id')

For the most part that generic relations is associated with one of these two models在大多数情况下,通用关系与这两个模型之一相关联

class Title(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    title_name = models.CharField(max_length=40)
    ....


class JobPosition(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    ...

Within a view function I am trying to figure out what model between Title and JobPosition is associated with a specific SectionLine instance so that i can determine what to do next.在视图函数中,我试图找出TitleJobPosition之间的模型与特定的SectionLine实例相关联,以便我可以确定下一步要做什么。

I now that I can access SectionLine.content_type to see the content type (for example, it prints titles_and_names | title - the app name is titles_and_names ) but I don't know what to compare it to...我现在可以访问SectionLine.content_type以查看内容类型(例如,它打印titles_and_names | title - 应用程序名称是titles_and_names )但我不知道将它与什么进行比较...

basically, if SectionLine.content_type == ???基本上, if SectionLine.content_type == ???

您可以使用 ContentType.objects.get_for_model 来比较https://docs.djangoproject.com/en/3.2/ref/contrib/contenttypes/#django.contrib.contenttypes.models.ContentTypeManager.get_for_model

if SectionLine.content_type == ContentType.objects.get_for_model(Title)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM