Remove relationship from ModelA to ModelB but do NOT remove from ModelB to ModeA in Django ManyToMany Fields

28 Views Asked by At

I have a this model structue,

ModelA:
  model_b = models.ManyToManyField(
        ModelB,
        blank=True,
    )
  ...

ModelB:
  ...

Now I want to delete the relationship from ModelA to ModelB using, model_a.model_b.clear() but I want model_b.model_a_set.all() to still retain the ModelB object. It's kinda I want independent OneToMany and ManyToOne relationship. How can I implement it?

PS: In my case ModelB always have relation to a single object of ModelA, if this can reduce the complexity of the implementation.

1

There are 1 best solutions below

0
Ezon Zhao On

Looks like you want a fk relation on ModelB

class ModelB(models.Model):
    model_a = models.ForeignKey(
        ModelA,
        # You may want other kinds of cascading mode here
        on_delete=models.CASCADE
    )

If this is the case (and after migration), you will then populate this field with data from the original m2m field.

for model_a in ModelA.objects.all():
    model_a.model_b.update(model_a=model_a)

Then you are free to remove the original m2m field