Search code examples
sqldjangodjango-modelsrelational-databasem2m

Django, how to have an array in model without M2M?


I want my model to have an array of other model's instances. Let me explain.

I have a Company model which has a localizations field which is supposed to be a set/array of addresses. Since one address can only be for one Company, M2M relationship seems wrong here.

When Company gets deleted, all of its localizations should also be deleted.

How do I accomplish that? (I don't use Postgres)


Solution

  • In this situation you want a ForeignKey (which is a many-to-one relationship). See the code below:

    class Company(models.Model):
        ...
    
    class Address(models.Model):
         company = models.ForeignKey(Comapny, on_delete=models.CASCADE, related_name="localizations")
         address_line_1 = models.CharField(max_length=255, blank=False)
         # Other fields you want
         ...
    

    Each Address points to one Company instance. But there is no limit on how many Addresss can point to a Company. In this sense, a company "has" many addresses.

    The related_name="localizations" argument, means that you can do company.localizations to get an array of the Address instances that point to that company.

    Finally, on_delete=models.CASCADE means that if you delete a Company instance, the Address instances that point to it will also be deleted.