我有一个与我的User类具有一对一关系的类。在这个类(称为UserLocations)中,我有一个字段是另一个类上的ManyToManyField(我们将这个模型称为Locations)。
在我的Locations类中,我有一个名为'abbreviation'的字段,它是位置名称的四字符缩写。我有一个前端网站,管理员可以在其中创建新用户或更新现有用户位置(基于缩写字段)。
当我要创建新用户时,如何根据“缩写”字段设置/更新ManyToMany字段?它是与Locations模型中的“缩写”字段相关的缩写列表。
# 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()
如果我误解了你的问题,请告诉我。