Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Custom field with default unique #181

Open
petrprikryl opened this issue Dec 30, 2024 · 1 comment
Open

Custom field with default unique #181

petrprikryl opened this issue Dec 30, 2024 · 1 comment
Labels
bug Something isn't working

Comments

@petrprikryl
Copy link

Example:

class UniqueField(models.CharField):
    def __init__(self, *args, **kwargs):
        kwargs.setdefault("unique", True)
        super().__init__(*args, **kwargs)


@pghistory.track()
class Foo(models.Model):
    slug = UniqueField()

Which leads to following migration:

        migrations.CreateModel(
            name='Foo',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('slug', foo_app.models.UniqueField(unique=True)),
            ],
        ),
        migrations.CreateModel(
            name='FooEvent',
            fields=[
                ('pgh_id', models.AutoField(primary_key=True, serialize=False)),
                ('pgh_created_at', models.DateTimeField(auto_now_add=True)),
                ('pgh_label', models.TextField(help_text='The event label.')),
                ('id', models.IntegerField()),
                ('slug', foo_app.models.UniqueField(unique=True)),
            ],
            options={
                'abstract': False,
            },
        ),

I think that FooEvent shouldn't have slug field with unique constraint as it prevents multiple tracking events for same Foo record.

Next, it is working correctly for plain CharField with explicit unique=True (constraint is not present in the event model). The problem seems to be custom fields with implicit defaults which deviates from Django's defaults.

Thanks for any opinion to this topic.

@wesleykendall wesleykendall transferred this issue from AmbitionEng/django-pgtrigger Jan 8, 2025
@wesleykendall
Copy link
Member

Yea, seems like pghistory does not work well with custom fields like this.

The workaround for now is to declare a custom event model https://django-pghistory.readthedocs.io/en/3.5.1/event_models/#custom-event-models and explicitly declare the field

Will leave this open as a known bug. I imagine the solution may be straightforward if someone wants to try to address it. I wont be able to get to this anytime soon

@wesleykendall wesleykendall added the bug Something isn't working label Jan 8, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

2 participants