django-polymorphic icon indicating copy to clipboard operation
django-polymorphic copied to clipboard

OneToOneField cannot be primary key

Open macropin opened this issue 11 years ago • 8 comments

This example

class Account(PolymorphicModel):
    user = models.OneToOneField(User, primary_key=True)

fails with Caught AttributeError while rendering: type object 'Account' has no attribute 'polymorphic_primary_key_name'

2c47db8fcc284a92d2c9769ba503603fbea92660 introduced a new way of determining pk's which specifically excludes OneToOneField fields: if f.primary_key and type(f)!=models.OneToOneField:

This issue was reported downstream 2 years ago at https://github.com/bconstantin/django_polymorphic/issues/17.

Why exclude OneToOneField's? The tests continue to pass after removing this restriction.

macropin avatar Aug 16 '13 02:08 macropin

Hi, thanks for your report. I think that code is there because an inherited model also uses a OneToOneField for the basetable_ptr field. This obviously needs to be fixed!

Currently I'm a bit busy (and maintain several packages). Would you be able to provide a nice test-case and pull request to fix this?

vdboor avatar Aug 16 '13 07:08 vdboor

Just to share: I had a similar issue, I guess. Fixed via monkey patch for now:

# Traceback
Stacktrace (most recent call last):
(...)
  File "django/forms/models.py", line 315, in _post_clean
    self.instance = construct_instance(self, self.instance, opts.fields, opts.exclude)
  File "django/forms/models.py", line 52, in construct_instance
    f.save_form_data(instance, cleaned_data[f.name])
  File "django/db/models/fields/related.py", line 1134, in save_form_data
    setattr(instance, self.name, data)
# Monkeypatch
from django.db.models.fields.related import OneToOneField
def _save_form_data(self, instance, data):
    if isinstance(data, self.rel.to):
        try:
            setattr(instance, self.name, data)
        except AttributeError, e:
            setattr(instance, self.attname, data.pk)
    else:
        setattr(instance, self.attname, data)

OneToOneField._save_form_data_ORIGINAL = OneToOneField.save_form_data
OneToOneField.save_form_data = _save_form_data

alanjds avatar Sep 24 '14 19:09 alanjds

I'm also having the exact same issue. If I understood the workings of django-polymorphic well enough I'd submit a pull request but...

DylanLukes avatar Jan 25 '15 07:01 DylanLukes

same issue

burrito-dev avatar Oct 12 '21 15:10 burrito-dev

same issue

NeielJair avatar Jul 21 '22 14:07 NeielJair

same issue

dilawerh avatar Sep 29 '22 01:09 dilawerh

Any updates on this issue?

Onur1991 avatar Mar 01 '23 18:03 Onur1991

Any update on this? I think have got the same issue, and I'm surprised this has been open for 10 years, specially since there's a fix... How can we move this forward?

piranna avatar Mar 08 '24 19:03 piranna