(DRF)如何更新外国钥匙字段

发布于 2025-02-04 16:03:47 字数 3744 浏览 1 评论 0原文

我有两个型号,帐户模型& 线程模型:

class Account(AbstractBaseUser, PermissionsMixin):
    
    class Meta:
        verbose_name_plural = "Account List"

    email = models.EmailField(max_length=255, unique=True)
    username = models.CharField(max_length=255, unique=True)
    name = models.CharField(max_length=255, default="")
    profile_image = models.ImageField(max_length=255, upload_to=profile_image_path, blank=True, null=True, unique=True)
    about = models.TextField(max_length=255, default='Write something about yourself...', blank=True)
    start_date = models.DateTimeField(default=timezone.now)
    is_staff = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    last_login = models.DateTimeField(auto_now=True)

    objects = AccountManager()

    USERNAME_FIELD = "email"
    REQUIRED_FIELDS = ["username", "name"]

    def __str__(self):
        return self.username
class Thread(models.Model):

    options = (('active', 'Active'), ('deactivated', 'Deactivated'))

    username = models.ForeignKey(Account, on_delete=models.CASCADE, to_field='username')
    alt = models.TextField(max_length=255, blank=True)
    image = models.ImageField(max_length=255, upload_to=thread_image_path, blank=True)
    content = models.TextField(blank=True)
    created = models.DateTimeField(blank=True, null=True, default=timezone.now)
    status = models.CharField(max_length=11, choices=options, default='active')

如果我已经创建了一个foreferkey的线程到帐户模型,我将无法更改用户名 帐户模型的模型,返回错误外键约束失败。我猜现有的线程模型需要用户名来指向。是否可以在view.py中创建自定义更新方法来自动更新foreferkey

这是我的view.py

class UserViewSet(viewsets.ModelViewSet):
    serializer_class = UserSerializer 
    queryset = Account.objects.all()
    permission_classes = (AllowAny,)

编辑: serializer.py

class ThreadSerializer(serializers.ModelSerializer):
    
    profile_image = serializers.SerializerMethodField('get_profile_image')
    created = serializers.DateTimeField(format="%d %B, %Y %H:%M:%S")
    
    class Meta:
        model = Thread
        fields = (
                  'id',
                  'username',
                  'profile_image',
                  'alt', 
                  'image', 
                  'content', 
                  'created', 
                  'status')
        
    def get_profile_image(self, thread):
        profile_image_url = thread.username.profile_image.url
        return profile_image_url

错误:

IntegrityError at /account/auth/user/1/
FOREIGN KEY constraint failed
Request Method: PUT
Request URL:    http://127.0.0.1:8000/account/auth/user/1/
Django Version: 4.0.4
Exception Type: IntegrityError
Exception Value:    
FOREIGN KEY constraint failed
Exception Location: c:\Users\85291\Desktop\vscode\my-app\web\env\lib\site-packages\django\db\backends\sqlite3\base.py, line 477, in execute
Python Executable:  c:\Users\85291\Desktop\vscode\my-app\web\env\Scripts\python.exe
Python Version: 3.10.2
Python Path:    
['C:\\Users\\85291\\Desktop\\vscode\\my-app\\web\\jtravel',
 'c:\\Users\\85291\\.vscode\\extensions\\ms-python.python-2022.6.3\\pythonFiles\\lib\\python\\debugpy\\_vendored\\pydevd',
 'C:\\Python310\\python310.zip',
 'C:\\Python310\\DLLs',
 'C:\\Python310\\lib',
 'C:\\Python310',
 'c:\\Users\\85291\\Desktop\\vscode\\my-app\\web\\env',
 'c:\\Users\\85291\\Desktop\\vscode\\my-app\\web\\env\\lib\\site-packages']
Server time:    Sun, 05 Jun 2022 16:40:53 +0800

I have two models, Account model & Thread model:

class Account(AbstractBaseUser, PermissionsMixin):
    
    class Meta:
        verbose_name_plural = "Account List"

    email = models.EmailField(max_length=255, unique=True)
    username = models.CharField(max_length=255, unique=True)
    name = models.CharField(max_length=255, default="")
    profile_image = models.ImageField(max_length=255, upload_to=profile_image_path, blank=True, null=True, unique=True)
    about = models.TextField(max_length=255, default='Write something about yourself...', blank=True)
    start_date = models.DateTimeField(default=timezone.now)
    is_staff = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    last_login = models.DateTimeField(auto_now=True)

    objects = AccountManager()

    USERNAME_FIELD = "email"
    REQUIRED_FIELDS = ["username", "name"]

    def __str__(self):
        return self.username
class Thread(models.Model):

    options = (('active', 'Active'), ('deactivated', 'Deactivated'))

    username = models.ForeignKey(Account, on_delete=models.CASCADE, to_field='username')
    alt = models.TextField(max_length=255, blank=True)
    image = models.ImageField(max_length=255, upload_to=thread_image_path, blank=True)
    content = models.TextField(blank=True)
    created = models.DateTimeField(blank=True, null=True, default=timezone.now)
    status = models.CharField(max_length=11, choices=options, default='active')

If I have already created a thread that is ForeignKey to the Account model, I am not able to change the username of the Account model, returning the error FOREIGN KEY constraint failed. I guess the existing Thread model require a username to point to. Is there way to create a custom update method in view.py to update the ForeignKey automatically?

Here is my view.py:

class UserViewSet(viewsets.ModelViewSet):
    serializer_class = UserSerializer 
    queryset = Account.objects.all()
    permission_classes = (AllowAny,)

EDIT:
serializer.py

class ThreadSerializer(serializers.ModelSerializer):
    
    profile_image = serializers.SerializerMethodField('get_profile_image')
    created = serializers.DateTimeField(format="%d %B, %Y %H:%M:%S")
    
    class Meta:
        model = Thread
        fields = (
                  'id',
                  'username',
                  'profile_image',
                  'alt', 
                  'image', 
                  'content', 
                  'created', 
                  'status')
        
    def get_profile_image(self, thread):
        profile_image_url = thread.username.profile_image.url
        return profile_image_url

Error:

IntegrityError at /account/auth/user/1/
FOREIGN KEY constraint failed
Request Method: PUT
Request URL:    http://127.0.0.1:8000/account/auth/user/1/
Django Version: 4.0.4
Exception Type: IntegrityError
Exception Value:    
FOREIGN KEY constraint failed
Exception Location: c:\Users\85291\Desktop\vscode\my-app\web\env\lib\site-packages\django\db\backends\sqlite3\base.py, line 477, in execute
Python Executable:  c:\Users\85291\Desktop\vscode\my-app\web\env\Scripts\python.exe
Python Version: 3.10.2
Python Path:    
['C:\\Users\\85291\\Desktop\\vscode\\my-app\\web\\jtravel',
 'c:\\Users\\85291\\.vscode\\extensions\\ms-python.python-2022.6.3\\pythonFiles\\lib\\python\\debugpy\\_vendored\\pydevd',
 'C:\\Python310\\python310.zip',
 'C:\\Python310\\DLLs',
 'C:\\Python310\\lib',
 'C:\\Python310',
 'c:\\Users\\85291\\Desktop\\vscode\\my-app\\web\\env',
 'c:\\Users\\85291\\Desktop\\vscode\\my-app\\web\\env\\lib\\site-packages']
Server time:    Sun, 05 Jun 2022 16:40:53 +0800

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

辞慾 2025-02-11 16:03:48

删除to_field ='用户名'

username = models.ForeignKey(Account, on_delete=models.CASCADE) 

这是错误的原因

delete to_field='username'

username = models.ForeignKey(Account, on_delete=models.CASCADE) 

it is a reason of an error

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文