0

I have two models that I want to relate with a many to many relationship. BuildingGroup and Building

My idea is that for example Building Group1 contains some Buildings and BuildingGroup2 contains other Buildings.

I think I should have set it up correctly, but the way it works now is that every BuildingGroup contains ALL of my Buildings, always. I can't delete a Building and selectively decide which building belongs to which group.

Here are my models:


class Building(models.Model):
    name  = models.CharField(max_length=120, null=True, blank=True)

    def __str__(self):
        return self.name


class BuildingGroup(models.Model):
    description           = models.CharField(max_length=500, null=True, blank=True)
    buildings             = models.ManyToManyField(Building, blank=True)

Is that the right way to set it up? And if so, how can I change it, so I can group it correctly??

Any help is highly appreciated!

Micromegas
  • 1,499
  • 2
  • 20
  • 49

1 Answers1

0

You have to change your database relations like below

class Building(models.Model):
  name  = models.CharField(max_length=120, null=True, blank=True)
  group = models.ManyToMany(BuildingGroup, related_name="buildings")

  def __str__(self):
    return self.name


class BuildingGroup(models.Model):
  name = models.CharField(max_length=500, null=True, blank=True)

Now, query like

group = BuildingGroup.objects.get(pk=10) # just a random id
rel_buildings = group.buildings.all()
anjaneyulubatta505
  • 10,713
  • 1
  • 52
  • 62
  • thank you my friend! I will try this tomorrow and will let you know. Just for my understanding: I implemented a m2m relation because a building can be part of many BuildingGroups and a BuildingGroup can have many Buildungs. Why can I not do this with m2m? Or why use a normal Foreign Key? – Micromegas Jun 11 '19 at 17:55
  • Because it's not m2m, it's 1-m. A building group can have multiple buildings but building cannot have a multiple building groups. – anjaneyulubatta505 Jun 12 '19 at 02:39
  • well, a Building can be part of multiple BuildingGroups.... Is that not the same? – Micromegas Jun 12 '19 at 06:49
  • I think it is must be m2m relationship, because I need to store for example building1 in BuildingGroup 1 and 2 and 3 – Micromegas Jun 12 '19 at 08:05
  • if it's the case then you can change the `ForeignKey` to `ManyToMany`. I'll update the code. – anjaneyulubatta505 Jun 12 '19 at 08:37
  • thank you so much Anjaneyulu. That helped alot. Also I realized I made a mistake in my previous question. So I asked anew but it is closely related. In case you are interested: https://stackoverflow.com/questions/56558396/how-to-overwrite-get-method-in-generic-retrieveapiview-in-django-rest-framework – Micromegas Jun 12 '19 at 09:05