Python 复杂查询

标签 python django python-3.x django-models django-rest-framework

我有以下模型:

class Restaurant(models.Model):
    name = models.CharField(max_length=100)


class UserPreference(models.Model):
    user = models.OneToOneField(User, on_delete=CASCADE)
    fruit = models.MantToManyField(Fruit)
    vegetable = models.MantToManyField(Vegetable)

class RestaurantPreference(models.Model):
    restaurant = models.OneToOneField(Restaurant, on_delete=CASCADE)
    fruit = models.MantToManyField(Fruit)
    vegetable = models.MantToManyField(Vegetable)

我如何使用首选项表在餐厅模型中查询

例如,我需要获得对特定用户具有相同偏好的餐厅?

请有想法的人帮帮我

非常感谢

最佳答案

如果您通过查询用户来获取用户偏好,您将获得相应的用户偏好,查询就像

user_preference = UserPreference.objects.get(user=user)
fruits = user_preference.fruit.all() # user's fruit preferences
vegetables = user_preference.vegetable.all() # user's vegetable preferences

现在你得到了用户所有的水果和蔬菜偏好。由此,您可以使用 django ORM 查询餐厅偏好

restaurant_preferences = RestaurantPreference.objects.filter(fruit__in=fruits, vegetable__in=vegetables)

关于Python 复杂查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53045099/

相关文章:

python - 查找 Python 数组中的最低相邻索引

python - 从 Jamfile 调用 python 脚本

javascript - Python 字典与 Javascript 对象有什么区别?

python - 将平均感知器标记器 POS 转换为 WordNet POS 并避免元组错误

python - Jupyter Notebook 和以前的输出

python - eventlet.monkey_patch() 抛出异常 : The SECRET_KEY setting must not be empty

javascript - 每次渲染react时刷新组件状态

python - 对 modelform_factory 表单中的字段进行重新排序

python - 输入 'n' 时无法打印最终语句

Python:如果行中只有 1 个单词,则替换数据框/列中的字符串