form.is_valid() gets more than one instance when my model have no id but two fields unique together

Hello fellow Django Users!

I’ve been facing some issues with form validation. And it completely makes sense. But I hope some of you people could help me. Let me (try) to explain.
There is a model:
-Not managed by me;
-With no id but unique_together;
I have to use this model as a field. ModelChoiceField works as a charm. It renders ok with some tweaking on the str function. But validation (trough form.is_valid()) turns out to be impossible given that the instance referred in request.POST is not a composite of the unique fields, but the first field of the model, and a MultipleObjectsReturned error is raised. Although understanding the problem itself is not a issue (at least for me, I hope I made the problem clear also for you, fellow Django User) I’m struggling to even come up with some workaround that does not involve create an id field.
Is it possible to set the value of the instance as a composite? Will it be queryed right? What should I do?

Thanks in advance for any insight.

Django models all function under the expectation that there is a single field primary key existing on all models.

If you’re working with models without any kind of primary keys, you will have problems trying to update them.

Solution: Create a single field primary key.

1 Like

Thanks for your response @KenWhitesell!
Just to be clear the model itself is not managed by Django and its updates are performed by a third party. But we have the model file on Django and fetch some data on it also. I was using the model via forms only to allow users set some parameters (the two fields as a unique are date and ~kind) and then generate some files. Guess I’ll have to talk to the third party then.

Yep, I understood that. But this is a fairly solid requirement for the Django ORM, at least as far as updates are concerned.

You could bypass the ORM by using raw SQL for your updates. (You could still use the ORM for queries.) That may be sufficient for your needs, but you would need to determine that.