djangodjango-modelsdjango-migrations

How to refactor a couple of fields from one model to another with FK relation


I currently have a model

class Car(models.Model):
    name = models.CharField(max_length=20)
    manufacturer_name = models.CharField(max_length=20)
    manufacturer_url = models.URLField()

Now I would like to extract the manufacturer information into its own model, so that I can get rid of redundant data. Like so:

class Manufacturer(models.Model):
    name = models.CharField(max_length=20)
    url = models.URLField()

class Car(models.Model):
    name = models.CharField(max_length=20)
    manufacturer = models.ForeignKey(Manufacturer, on_delete=models.CASCADE)

Doing this however the Django migration tool just detects this as "delete fields" and "add fields". Can Django somehow do this migration automatically? Or will I have to write those migrations myself. It seems like a common use case, so I figured maybe Django has something in store for ootb.


Solution

  • No as far as my knowledge there is nothing in django to deal with this situation What i suggest is first dont delete the manufacturer_name field from cars:

    class Manufacturer(models.Model):
        name = models.CharField(max_length=20)
        url = models.URLField()
    
    class Car(models.Model):
        name = models.CharField(max_length=20)
        manufacturer_name = models.CharField(max_length=20)
        manufacturer_url = models.URLField()
        manufacturer = models.ForeignKey(Manufacturer, on_delete=models.CASCADE)
    
    ##then using 
    python manage.py shell 
    from app.models import *
    getallcars = Car.objects.all()
    for car in getallcars:
        getmanufacturer,created = Manufacturer.objects.getorcreate(name=car.manufacturer_name ,manufacturer_url =car.manufacturer_url)
    

    Then you can delete manufacturer_name and manufacturer_url