使用django和查询创建中的sqlite访问表

发布于 2025-01-25 08:44:53 字数 3887 浏览 4 评论 0 原文

我想使用django从Table1,数据库访问数据,并根据其他表访问查询。例如:从表1(用户,日期,小时:分钟,城市,标签)访问数据和表2(用户,日期:小时:分钟,纬度,纵向),如果小时:分钟在两个表中相同,则我需要使用一些值(North,South,East,West)更新现场标签。 我尝试使用objectss.filter在用户(日期)上访问Table1的数据,但是我认为这不是一个好方法,因为它不会给我从行中的值。我从,但我无法正确执行此操作并完成它。 在第二部分中,我一直在考虑用IF做些事情,但仍然不确定。一开始,我需要从表1访问数据。

编辑: 我想在上传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
    })

I want to access data from table1, from my database and to make a query based on other table, using django. For example: access data from table1 (user, date, hour:minutes, city, tag) and table 2 (user, date: hour:minute, latitude, longitudinal) and if the hour:minutes are the same in both table, I need to update the field tag with some values (North, South, East, West).
I tried to access the data from table1 with objects.filter on user, date, but I think that it's not a good method, because it doesn't give me the values from the row. I read the documentation from https://docs.djangoproject.com/en/4.0/topics/db/queries/#copying-model-instances but I can not manage to do this correctly and finish it.
And for the second part, I was thinking to make something with an if, but still not sure. In the beginning I need to access data from the table1.

Edit:
I want to make this changes in the file uploadCoord_File_view, when I upload the excel file.
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
    })

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

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

发布评论

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

评论(1

时光病人 2025-02-01 08:44:53

我无法在行 user = user.objects.get(id = user_id)中找到 user_id 来源。它是来自读取器还是可以使用 user = request.user

如果我的假设是正确的,那么我认为您可以首先在 loop的之前先获取用户,用户和本地化表:

@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 get 返回无匹配:您将获得错误:

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

I can't figure out in the line user = User.objects.get(id = user_id) where user_id is coming from. Is it coming from reader or can you use user = request.user?

If my assumptions are correct, then I think you can first get the User, UserAcoount and Localization tables first before the for loop:

@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)

   ...

Then you can do the matching and updating like this:

###### 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')

It is best to put all get queries in a try/except statement, otherwise you'll get an error if the get returns no matches:

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