Home > Software engineering >  (DRF) How to update a foreignkey field
(DRF) How to update a foreignkey field

Time:06-05

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

CodePudding user response:

delete to_field='username'

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

it is a reason of an error

  • Related