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

unique=True #179

Open
the-moog opened this issue Aug 2, 2022 · 2 comments
Open

unique=True #179

the-moog opened this issue Aug 2, 2022 · 2 comments

Comments

@the-moog
Copy link

the-moog commented Aug 2, 2022

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
Copy link

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
Copy link
Author

the-moog commented Dec 5, 2022

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants