Chad
Chad

Reputation: 40

Can two models reference each other by ForeignKey?

I have two models

class Customer(models.Model):
    name = models.CharField(max_length=255, unique=True)
    default_contact = models.ForeignKey("CustomerContact", verbose_name="...", related_name="default_contacts", null=True, on_delete=models.SET_NULL)
    etc.

And

class CustomerContact(models.Model):
    customer = models.ForeignKey(Customer, related_name='contacts')
    user = models.OneToOneField(User, related_name='user_contacts', on_delete=models.SET_NULL)
    address = models.ForeignKey(CustomerAddress, ....)

In this example Customer points to CustomerContact. At the same time CustomerContact points to Customer.

My coworker says that pointing Customer points to CustomerContact violates the OneToMany nature of ForeignKey. What am I doing wrong?

Upvotes: 2

Views: 724

Answers (1)

NixonSparrow
NixonSparrow

Reputation: 6388

As I can see you want to have many CustomerContact related to one Customer, but Customer can also pick his favourite (or one can be set by manager). It's valid approach.

It can go both ways, as long as you will secure related_names properly.

default_contact = models.ForeignKey("CustomerContact", ... related_name="default_contacts") <= should be changed

default_contacts should be changed (i.e. to default_for_customers) because this name is for reversed relation, so actually for CustomerContact. It means, that you can use it in the following situation:

cc = CustomerContact.objects.get(id=1)
cc.default_for_customers.all()  <= this will return QuerySet of Customer objects that is default for

It's simplier and less confusing.

Upvotes: 2

Related Questions