Home > Mobile >  Check content type with if statement to determine what to do
Check content type with if statement to determine what to do

Time:11-17

I have django model with a generic relation associated.

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.

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...

basically, if SectionLine.content_type == ???

CodePudding user response:

You can use ContentType.objects.get_for_model to compare 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)

  • Related