furious-luke / django-address

A Django address model and field. Addresses may be specified by address components or by performing an automatic Google Maps lookup.
BSD 3-Clause "New" or "Revised" License
431 stars 181 forks source link

unique=True #179

Open the-moog opened 2 years ago

the-moog commented 2 years ago

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

AntoineKoiko commented 1 year ago

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

the-moog commented 1 year ago

Thanks for the explanation I will update my code as you suggest.