使用 django 和查询创建在 sqlite 中访问 table

Access table in sqlite using django and query creation

我想使用 django 从 table1 从我的数据库访问数据并基于其他 table 进行查询。例如:从table1(用户、日期、hour:minutes、城市、标签)和table2(用户、日期:hour:minute、纬度、经度)访问数据和如果 hour:minutes 在两个 table 中相同,我需要用一些值(北、南、东、西)更新字段标签。 我尝试从 table1 和 objects.filter 访问用户日期的数据,但我认为这不是一个好方法,因为它没有给我行中的值。我从 https://docs.djangoproject.com/en/4.0/topics/db/queries/#copying-model-instances 阅读了文档,但我无法正确完成此操作并完成它。 对于第二部分,我想用 if 做点什么,但还是不确定。一开始我需要从 table1.

访问数据

编辑: 当我上传 excel 文件时,我想在文件 uploadCoord_File_view 中进行此更改。 model.py

class Localization(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    date = models.CharField(max_length=10, blank=False, null= False)
    time = models.CharField(max_length=5, blank=False, null= False)
    city = models.CharField(max_length=10, blank=False,, null = True)
    tag = models.CharField(max_length=10, default=None, null = True)

    def __str__(self):
        return f"{self.user}"



class Coordinates(models.Model):
    user = models.ForeignKey(UserAccount, related_name='hr_user', on_delete=models.CASCADE)
    date = models.CharField(max_length=10, blank=False, null= False)
    time = models.CharField(max_length=5, blank=False, null= False)
    latitude = models.CharField(max_length=10, blank=False, null= False)
    longitudinal = models.CharField(max_length=10, blank=False, null= False)

    def __str__(self):
        return f"{self.user}"

view.py

@login_required(login_url='login') 
def uploadLocalization_file_view(request):
        form = CsvFileForm(request.POST, request.FILES)

        if form.is_valid():
            form.save()
            form = CsvFileForm()

            obj = CsvFileModel.objects.get(activated=False)
            with open(obj.file_name.path, 'r') as f:
                reader = csv.reader(f)

                for i, row in enumerate(reader):
                    if i==0: 
                        pass
                    else: 
                       
                        date = row[0]
                        user = User.objects.get(id = user_id)
                        Localization.objects.create(
                            date=date,
                            time = row[1],
                            city = row[2],
                        )
                        t= convert_time2sec(row[1])

                obj.activated=True
                obj.save()
                return redirect('../uploadCoord_file_view')
        return render(request, 'uploadFile.html', {
        'importFileForm': form
    })

@login_required(login_url='login') 
def uploadCoord_file_view(request):
        form = CsvFileForm(request.POST, request.FILES)

        if form.is_valid():
            form.save()
            form = CsvFileForm()

            obj = CsvFileModel.objects.get(activated=False)
            with open(obj.file_name.path, 'r') as f:
                reader = csv.reader(f)

                for i, row in enumerate(reader):
                    if i==0: 
                        pass
                    else: 
                       
                        date = row[0]
                        user = User.objects.get(id = user_id)
                        Coordinates.objects.create(
                            date=date,
                            time = row[1],
                            latitude = row[2],
                            longitudinal = row[3],
                        )
                        t = convert_time2sec(row[1])
                        ###### Here I need to access the table Localization and create the query
                obj.activated=True
                obj.save()
                return redirect('../results')
        return render(request, 'uploadCoordFile.html', {
        'importCoordFileForm': form
    })

我无法弄清楚 user = User.objects.get(id = user_id) 行中 user_id 的来源。它来自 reader 还是可以使用 user = request.user

如果我的假设是正确的,那么我认为您可以在 for 循环之前先获取 User、UserAcount 和 Localization 表:

@login_required(login_url='login') 
def uploadCoord_file_view(request):
    
    # Get the user
    user = request.user

    # Access the Localization table of the specific user
    localization = Localization.objects.get(user=request.user)

    # Access the UserAccount (you did not provide that model, so I am guessing
    user_account = UserAccount.objects.get(user=request.user)

   ...

然后你可以像这样进行匹配和更新:

###### Here I need to access the table Localization and create the query

# Filter all Coordinates that have the same date and user as the Localization table
coordinates = Coordinates.objects.filter(date=localization.date, user=user_account)

# Update the values of all the matches
coordinates.update(latitude='North', longitude='West')

最好将所有 get 查询放在一个 try/except 语句中,否则如果 get returns 没有匹配,你会得到一个错误:

try:
    # Access the Localization table of the specific user
    localization = Localization.objects.get(user=request.user)
except Localization.DoesNotExist
    # Code to handle what should happen if no match exists