Dynamically populate constraints in Field.contribute_to_class

Ah, the fact that it didn’t throw an exception on the non-inherited model was due I think to the bug described above - adding another constraint into that model triggered the exception on that one.

So the error I’m dealing with is indeed that the CreateModel operation is incorrectly “seeing” a constraint (that will be handled elsewhere).

So, interestingly, explicitly added constraints are not present in the “fake” model that migrations use, but this class is passed to the contribute_to_class function, so “automatic” constraints added here still get added.

In my case, I was able to avoid adding the constraint if cls.__module__ == '__fake__', but this feels like a dirty solution - I’d be keen to find why cls._meta.constraints is empty when building migrations…

I would also like if that worked, my use case is

class PageTypeForeignKey(models.ForeignKey):
    def contribute_to_class(self, cls, name, *args, **kwargs):
        super().contribute_to_class(cls, name, *args, **kwargs)
        cls._meta.constraints.append(
            models.UniqueConstraint(
                fields=[name, "lang"],
                name=f"{cls._meta.app_label}_{cls.__name__.lower()}_{name}_and_lang",
            )
        )

and makemigrations doesn’t create the constraints

I tried the metaclass solution and it still didn’t work without defining constraints = [] in Meta

but apparently pg now works when doing it in contribute_to_class and having constraints defined in Meta (tested by a friend in pg)

I tested both in sqlite (with constraints = [] in Meta) and both work