Opened 3 years ago

Closed 3 years ago

#33341 closed Bug (needsinfo)

The PrimaryKey of an Unmanaged Model is incorrectly regognized (accessing database VIEW)

Reported by: Janne Owned by: nobody
Component: Uncategorized Version: 3.2
Severity: Normal Keywords: Unmanaged model, Database VIEW, postgres
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 have used the following method earlier successfully with Django 3.0.6, but now there's a bug.

But now the 3.2.9 catches a "Gotcha" in django/db/models/fields/related.py in "get_instance_value_for_fields" (line 662), I believe incorrectly.

Currently I have:

– A view on postgres (to access a managed model "Rules", with default id as PK): CREATE OR REPLACE VIEW rules_view

– Unmanaged model to access "Rules" data via "rules_view" view like this:

class LinkedRules(Rules)
    ....
    class Meta:
        managed = False
        db_table = 'rules_view

The problem: I am able to retrieve the data with, only with a raw SQL query, after changing the field name from id to rules_ptr_id like this:

LinkedViewRules.objects.raw(f'SELECT id as rules_ptr_id , ...

Hope this helps.

PS. Couldn't test my current project with old <3.2 version, due to other incompatibilities (with numpy array withespaces).
(Table names are paraphrased, hopefully without errors)

Hint from django/db/models/fields/related.py:

# Gotcha: in some cases (like fixture loading) a model can have
# different values in parent_ptr_id and parent's id. So, use
# instance.pk (that is, parent_ptr_id) when asked for instance.id.


Change History (1)

comment:1 by Carlton Gibson, 3 years ago

Resolution: needsinfo
Status: newclosed

Hi. I don't think there's quite enough detail here to see what you're issue is.

In general, using managed=False works with views, and has for many years, see e.g. #16320.

You mention the primary key, but don't provide the model definition. Ensure you're declaring a field as primary_key=True.
There was a recent walk through on using views with Django (targeting Postgres) that might help you if you walk through it.

Otherwise, it looks like a usage issue, so you'll need to use one of the support channels. See TicketClosingReasons/UseSupportChannels.

If you can provide a sample project or a failing test case showing a fault in Django, then very happy to re-open and have a look.
Thanks.

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