Opened 12 hours ago

Last modified 11 hours ago

#36449 assigned Bug

Mismatched fields in composite primary key ForeignObject example model

Reported by: Jacob Walls Owned by: Jacob Walls
Component: Documentation Version: 5.2
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: yes UI/UX: no

Description

The field types on this example model are not correct; the primary key of Order is CharField, and Product is IntegerField:

class Foo(models.Model):
    item_order_id = models.IntegerField()
    item_product_id = models.CharField(max_length=20)
    item = models.ForeignObject(
        OrderLineItem,
        on_delete=models.CASCADE,
        from_fields=("item_order_id", "item_product_id"),
        to_fields=("order_id", "product_id"),
    )

It should be:

class Foo(models.Model):
    item_order_id = models.CharField(max_length=20)
    item_product_id = models.IntegerField()
    item = models.ForeignObject(
        OrderLineItem,
        on_delete=models.CASCADE,
        from_fields=("item_order_id", "item_product_id"),
        to_fields=("order_id", "product_id"),
    )

Found this while trying to write a test with these models, e.g. this fails:

In [28]: f = Foo.objects.first()

In [29]: f.item
Out[29]: <OrderLineItem: OrderLineItem object ((1, '1'))>

In [30]: Foo.objects.filter(item=item)
Out[30]: ---------------------------------------------------------------------------
UndefinedFunction                         Traceback (most recent call last)
File ~/django/django/db/backends/utils.py:105, in CursorWrapper._execute(self, sql, params, *ignored_wrapper_args)
    104 else:
--> 105     return self.cursor.execute(sql, params)

UndefinedFunction: operator does not exist: character varying = integer
LINE 1: ...."item_order_id", "models_foo"."item_product_id") = ('1', 1)...
                                                             ^
HINT:  No operator matches the given name and argument types. You might need to add explicit type casts.

While here, also suggest documenting inside the caveats about how ForeignObject differs from ForeignKey that the on_delete argument is ignored.

Change History (1)

comment:1 by Jacob Walls, 11 hours ago

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