0

I have two models as shown below. ArticlePost is related to Article by a Foreign Key. I'm wanting to remove name as a primary key on Article and instead have the Django default id field. What is the best steps to do this so that all related ArticlePosts will maintain the correct Foreign Key to Article?

class Article(models.Model):

    name = models.CharField(max_length=200, primary_key=True)

class ArticlePost(models.Model):

    article = models.ForeignKey(Article, null=False, db_index=True)
    created_at = models.DateTimeField(auto_now_add=True)
    comment = models.TextField(blank=True)
mohevi
  • 63
  • 2
  • 8
  • remove the `primary_key` from the name column, then it will automatically use the django's default id as the primary key. – Muhammad Shoaib Aug 04 '16 at 08:21
  • will this cascade to the related models as well? Also trying that gives me `You are trying to add a non-nullable field 'id' to Article without a default; we can't do that (the database needs something to populate existing rows).` – mohevi Aug 04 '16 at 08:58
  • no it will not, for cascading you will have to do this `models.ForeignKey(name, on_delete=models.CASCADE)`. The message you are receiving is that you have already populated the data in the table, so it need's to set the default value when you try to make new migration for the table. – Muhammad Shoaib Aug 04 '16 at 10:10
  • I understand that I have data already there. What I need is for the default Django `id` field to be added and for all `ArticlePost` objects related by Foreign Key to be updated so that they maintain their reference to the same `Article`. I don't see how how the default ID field is set with your response? Also, I don't see how the existing relations are updated? – mohevi Aug 04 '16 at 10:35

0 Answers0