首页 > 解决方案 > 在一个字段中保存多个值(Django)

问题描述

问题:

我有一个模型,它引用了 django 的基本用户模型。现在,如果我提交表单,Django 会通过用新数据替换现有数据来更新我的数据库。我希望能够访问它们。(在重量和日期字段中)

模型文件:

我在这里看到了其他帖子,他们通过指定外键解决了一个问题,但这并没有为我解决。

from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
# Create your models here.
class Profile(models.Model):
      user = models.ForeignKey(User, on_delete=models.CASCADE)
      weight = models.FloatField(max_length=20, blank=True, null=True)
      height = models.FloatField(max_length=20, blank=True, null=True)
      date = models.DateField(auto_now_add=True)
      def __str__(self):
          return self.user.username

      @receiver(post_save, sender=User)
      def save_user_profile(sender, instance, created, **kwargs):
      if created:
      Profile.objects.create(user=instance)

视图文件:

这是我保存从名为 WeightForm 的表单中获取的数据的地方

from django.shortcuts import render
from django.contrib.auth.models import User
from django.http import JsonResponse
from django.shortcuts import get_object_or_404
from users import models
from users.models import Profile
from .forms import WeightForm

def home(request):
    form = WeightForm()
    if request.is_ajax():
       profile = get_object_or_404(Profile, id = request.user.id)
       form = WeightForm(request.POST, instance=profile)
       if form.is_valid():
          form.save()
          return JsonResponse({
            'msg': 'Success'
        })
       
    
return render(request, 'Landing/index.html',{'form':form})

我尝试了什么:

我曾经与这个模型有一个 OneToOneField 关系,但正如你所看到的,根据我在这个网站上看到的答案,我将它更改为外键。

谢谢,如果你在我的混乱中走到这一步:D

标签: pythondjangomodel

解决方案


我不完全理解您所说的“我希望能够访问它们。(在重量和日期字段中)”的意思,但我想您希望用户也能够看到他们以前的体重和日期数据,所以你可以尝试这样做:

在你的 models.py 中尝试这样做,

class Profile(models.Model):
      user_id = models.AutoField(primary_key=True)
      user = models.ForeignKey(User, on_delete=models.CASCADE)
      height = models.FloatField(max_length=20, blank=True, null=True)
      def __str__(self):
          return self.user.username

class UserData(models.Model):
      Data_id = models.AutoField(primary_key=True)
      user_id = models.ForeignKey(Profile, on_delete=models.CASCADE)
      weight = models.FloatField(max_length=20, blank=True, null=True)
      date = models.DateField(auto_now_add=True)

然后你可以为这两个模型使用单独的表格并将它们组合使用。


推荐阅读