djangodjango-4.0

How to access the names of fields in Django UniqueConstraint?


Accepted answer for original question. Still not OK for "edit 1" (below)


Original Question

I want to access the field names when declared in Meta class :

class Book(models.Model):
    name = CharField(...)
    author = CharField(...)

    class Meta:
        constraints = [
            UniqueConstraint(
                # fields=['name', 'author'],       # solution 1
                Lower("name"), Lower("author"),    # solution 2
                name="unique__book_author",
            ),
        ]

With solution 1, I access with Book._meta.constraints[0].fields => ('name', 'author').

With solution 2, Book._meta.constraints[0].fields is empty :'(

Any idea ?

See https://docs.djangoproject.com/en/4.1/ref/models/constraints/


edit 1

All fields are not necessarily a function like Lower. If "author" is not a CharField but FKField, *expressions could be :

UniqueConstraint(Lower("name"), "author", name="unique__book_author")

Solution

  • Give this a try:

    fileds = []
    for expression in Book._meta.constraints[0].expressions:
        fields.append(expression.lhs.name)
    
    print(fileds)
    # Output: ['name', 'author']
    

    Update

    to get the constraints that are not expressions try this

    filed_names = Book._meta.constraints[0].columns