django-address
django-address copied to clipboard
unique=True
I have a model that uses an AddressField.
And, as as it seems sensible to me that no two suppliers could share the same address and thus to help prevent data duplication, I have set unique=True.
class Supplier(models.Model):
address = AddressField(blank=True, null=True, unique=True, default=None, help_text='Contact address')
I get this warning:
WARNINGS:
items.Supplier.address: (fields.W342) Setting unique=True on a ForeignKey has the same effect as using a OneToOneField.
HINT: ForeignKey(unique=True) is usually better served by a OneToOneField.
My address is not used in any relations but I guess the internal workings of AddressField() are?.
Is using unique in this way incorrect or is this a bug?
Python 3.9.13 Django 4.0.6 address 0.2.8
AddressField is a FroeignKey field behind the hood and the warning you've got is due to Django behavior.
Effectively, if you want that a Foreign key is unique in your table is similar to a One-To-One relation and in Django is more optimized and conventional to describe this kind of relation with a OneToOneField
So, custom your version of DjangoAddress with this Field corresponding of use cases where your addresses can't be attach to two address could be an idea, but in order that Django address corresponding to the largest use cases, the ForeignKey field is more appropriate
Thanks for the explanation I will update my code as you suggest.