【问题标题】:Django User Model with ManyToMany relationship, how to update/ create new profile with relationship?具有多对多关系的 Django 用户模型,如何更新/创建具有关系的新配置文件?
【发布时间】:2019-02-28 20:56:19
【问题描述】:

我有一个类与我的 User 类具有一对一的关系。在这个类(称为 UserLocations)中,我有一个字段,它是另一个类上的 ManyToManyField(我们将此模型称为 Locations)。

在我的 Locations 类中,我有一个名为“abbreviation”的字段,它是位置名称的四个字符的缩写。我有一个前端网站,管理员可以在其中创建新用户或更新现有用户位置(基于缩写字段)。

当我要创建一个新用户时,我将如何根据“缩写”字段设置/更新该 ManyToMany 字段?它是与 Locations 模型中的“缩写”字段相关的缩写列表。

【问题讨论】:

    标签: django django-models many-to-many manytomanyfield


    【解决方案1】:
    # Assuming you get the chosen abbreviation in a variable called location_abbreviation:    
    desired_location = Location.objects.get(abbreviation=location_abbreviation)
    user = User.objects.create(...)
    user_location = UserLocation.objects.create(user=user, ...)
    user_location.locations = [desired_location]
    user_location.save()
    

    如果我误解了你的问题,请告诉我。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-01
      • 2018-06-28
      • 2020-02-09
      • 1970-01-01
      • 1970-01-01
      • 2017-09-26
      • 2015-10-21
      • 2015-08-25
      相关资源
      最近更新 更多