Django migration error :you cannot alter to or from M2M fields, or add or remove through= on M2M fields

后端 未结 7 1643
梦如初夏
梦如初夏 2020-12-12 18:48

I\'m trying to modify a M2M field to a ForeignKey field. The command validate shows me no issues and when I run syncdb :

ValueError: Cannot alter field xxx i         


        
相关标签:
7条回答
  • 2020-12-12 19:46

    I had the same problem and found this How to Migrate a ‘through’ to a many to many relation in Django article which is really really helped me to solve this problem. Please have a look. I'll summarize his answer here,

    There is three model and one(CollectionProduct) is going to connect as many-to-many relationship.

    This is the final output,

    class Product(models.Model):
        pass
    
    
    class Collection(models.Model):
        products = models.ManyToManyField(
            Product,
            blank=True,
            related_name="collections",
            through="CollectionProduct",
            through_fields=["collection", "product"],
        )
    
    
    class CollectionProduct(models.Model):
        collection = models.ForeignKey(Collection, on_delete=models.CASCADE)
        product = models.ForeignKey(Product, on_delete=models.CASCADE)
    
        class Meta:
            db_table = "product_collection_products"
    

    and here is the solution,

    The solution

    Take your app label (the package name, e.g. ‘product’) and your M2M field name, and combine them together with and underscore:

    APPLABEL + _ + M2M TABLE NAME + _ + M2M FIELD NAME

    For example in our case, it’s this:

    product_collection_products

    This is your M2M’s through database table name. Now you need to edit your M2M’s through model to this:


    Also found another solution in In Django you cannot add or remove through= on M2M fields article which is going to edit migration files. I didn't try this, but have a look if you don't have any other solution.

    0 讨论(0)
提交回复
热议问题