【问题标题】:In the Django address module, how do I search for an entity by a related entity's column that isn't a primary key?在 Django 地址模块中,如何通过非主键的相关实体列搜索实体?
【发布时间】:2020-06-24 15:01:38
【问题描述】:

我正在使用带有 django-address 模块的 Django 3 和 Python 3.7 -- https://github.com/furious-luke/django-address。特别是它提供了两种模型...

  Country
    name
    code

  State
    name
    code
    country -> Country

如何根据特定国家/地区代码搜索州?如果我只是按主键搜索,我可以写

def get_object(self, pk):
    try:
        return State.objects.filter(country=pk)
    except Coop.DoesNotExist:
        raise Http404

但是,如果我使用国家代码搜索州,我不清楚如何编写 Django 查询。

【问题讨论】:

    标签: python-3.x django django-models filter


    【解决方案1】:

    如果您的 country's code 不是唯一的,您可以使用:

    State.objects.filter(code=your_code)
    

    如果此代码是唯一的,您可以使用以下方式之一:

    # Way 1 
    State.objects.get(code=your_code)
    # Way 2 
    State.objects.first(code=your_code)
    # Way 3
    State.objects.filter(code=your_code).first()
    

    希望对您有所帮助!

    【讨论】:

    • 谢谢,但它不起作用。呈现的查询是查询“state.code”而不是“country.code”——' SELECT address_state.id, address_state.name, address_state.code, address_statecountry_id FROM address_state INNER JOIN address_country ON (address_state.country_id = address_country.id) 其中address_state.code = 'US' ORDER BY@7644@7644@0@19 @ASC,address_state.nameASC;'
    猜你喜欢
    • 2012-10-02
    • 1970-01-01
    • 1970-01-01
    • 2021-07-13
    • 1970-01-01
    • 2022-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多