Django 应用迁移

Django application migration

我有一条 class 推文,我正在尝试向其中添加用户模型,以便用户可以拥有多条推文,但一条推文仅属于一个用户。

class Tweet(models.Model):
  context = models.TextField(blank=True, null=True)
  image = models.FileField(upload_to='images/', blank=True, null=True)

当我尝试迁移时出现此错误:

ValueError: invalid literal for int() with base 10: 'Anonymous'

我有一个user = models.ForeignKey(User, on_delete=models.CASCADE, default="anonymous")

但我删除了它,错误仍然存​​在

删除它无济于事,因为它已经在 migration 文件中。因此,您还需要删除迁移文件。

如果您想将 User 用户名 anonymous 一起使用,那么您可以为此使用可调用对象:

from django.conf import settings

def <b>get_anonymous</b>():
    if hasattr(get_anonymous, 'result'):
        return get_anonymous.result
    from django.contrib.auth import get_user_model
    User = get_user_model()
    result = get_anonymous.result = User.objects.get(username='Anonymous')
    return result

class Tweet(models.Model):
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        default=<b>get_anonymous</b>
    )
    context = models.TextField(blank=True, null=True)
    image = models.FileField(upload_to='images/', blank=True, null=True)

但这只适用于 User 记录 username='Anonymous' 的情况。如果没有这样的记录,人们通常使用NULL来表示一个丢失的用户,所以:

from django.conf import settings

class Tweet(models.Model):
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        <b>null=True</b>,
        default=<b>None</b>
    )
    context = models.TextField(blank=True, null=True)
    image = models.FileField(upload_to='images/', blank=True, null=True)

Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.