gpt4 book ai didi

python - 如何在 Django View 中将用户登录字段与其他用户进行比较

转载 作者:太空宇宙 更新时间:2023-11-04 09:56:12 25 4
gpt4 key购买 nike

假设我有以下模型:

import ephem

class Person(models.Model):
username = models.ForeignKey(User, blank=False)
slug = models.SlugField(blank=False)
location = ForeignKey(Location, blank=True) # return longitude & latitude city from Pyephem library
city = models.CharField(max_length=255, blank=False, default='')

def __str__(self):
return self.username

def get_city(self):
city = ephem.Observer()
city.lon = float(self.location.longitude)
city.lat = float(self.location.latitude)
return city # return city from location field

def save(self, *args, **kwargs):
if not self.pk:
self.slug = slugify(self.username)
super(Person, self).save(*args, **kwargs)

如何在 django 的 View 中以编程方式比较登录用户的属性和属性的其他用户?这是基于 slug 的用户名字段,还有一个来自其他 python 库 (Pyephem) 的附加对象,如下所示:

def detail(request, slug):
instance = Person.objects.all()
city = ........ # City from city fields at Person model, the city's value from current user logged have their value as city0 and city's values for other user have value as city1, city2, city3 Et seq...

for distance in instance:
# if current user logged are visiting other user detail then compare them each other
do something for city0 and city1, city0 and city2, city0 and city3 Et seq....
distance = ... # calculate distance of city's user logged & city's other user
# I'm not sure what to do in this area so it will get the results of comparing between attribute of current user logged and attribute of other user

return render(
request, "detail.html",
{
'distance': distance,
}
)

*更新

我根据@cezar 的回答更新了上面的模型并添加了城市的功能:

最佳答案

根据我的了解,很可能许多用户在您的模型中得到了一个 slug。因此,如果您想比较已登录的用户和带有一些 slug 的用户组,我会生成 QuerySet,然后进行迭代。

def detail(request, slug=None):
instances = Person.objects.filter(slug=slug)

if instances.count() == 0:
return HttpResponse('Slug returns 0 matches')
else:
for object in instances:
do something for city0 and city1

好的,感谢您提供更多详细信息!现在更新后我认为 request.user 对象就是你要找的:

def calculate_distance(user1, user2):
#do something here like:
#user1.location.lat user2.location.long etc.
return distance_between

def detail(request, slug=None):
instance = Person.objects.get(slug=slug)
observer_user = request.user

#added below variable to clarify code
user_to_be_observed = instance

return calculate_distance(observer_user, user_to_be_observed)

关于python - 如何在 Django View 中将用户登录字段与其他用户进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45752252/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com