Opened 3 years ago

Closed 3 years ago

#33614 closed Bug (invalid)

Django's object creation when using GenericForeignKeys results in different ContentType model id's

Reported by: Lucas Zocco Owned by: nobody
Component: contrib.contenttypes Version: 4.0
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

I've created a Document model that has a GenericFK to another model, however I have noticed that the related_type id is different depending on how the object is created. It seems to be wrong if done in the manner explained in the official documentation (https://docs.djangoproject.com/en/4.0/ref/contrib/contenttypes/#generic-relations-1) where the object is directly assigned to related_object instead of creating the GenericForeignKey by setting the related_type and related_id individually.

A small code snippet to illustrate:

class Document(BaseModel):
    related_id = models.UUIDField(
        null=True,
        blank=True,
        db_index=True,
        help_text=("The UUID of the origin model, which this flag came from."),
    )
    related_type = models.ForeignKey(
        ContentType,
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        help_text="Type that the Subject id relates to",
    )
    related = GenericForeignKey("related_type", "related_id")

doc1 = Document(data=b'',
            related=company)

doc2 = Document(data=b'',
            related_type=ContentType.objects.get_for_model(company),
            related_id=company.id)

print(ContentType.objects.get_for_model(company).id)
>>> 23

print(doc1.related_type.id)
>>> 148

print(doc2.related_type.id)
>>> 23

For reference: There's no object with id 148 in the ContentTypes table so I'm not sure where it's getting it from.

Change History (1)

comment:1 by Simon Charette, 3 years ago

Resolution: invalid
Status: newclosed

I unfortunately cannot reproduce your reported issue on the latest version of Django with your provided instructions (Defining a Company model of my own with no fields).

Please re-open with a set of instructions that reproduces against a supported version of Django (e.g. a sample project with a command or test case that demonstrates an assertion failure).

Note: See TracTickets for help on using tickets.
Back to Top