开发者

Django ManyToManyField error object has no attribute 'location_set'

开发者 https://www.devze.com 2023-02-23 05:11 出处:网络
This seems like a really trivial question, but it is killing me. models.py 开发者_开发技巧class Location(models.Model):

This seems like a really trivial question, but it is killing me.

models.py

开发者_开发技巧class Location(models.Model):
    place = models.CharField("Location", max_length=30)
    [...]

class Person(models.Model):
    first = models.CharField("First Name", max_length=50)
    [...]
    location = models.ManyToManyField('Location')

From the shell:

>>> from mysite.myapp.models import *
>>> p = Person.objects.get(id=1)
>>> p
<Person: bob >
>>> l = Location(place='123 Main')
>>> p.location_set.add(l)
>>> p.save()
Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: 'Person' object has no attribute 'location_set'

I'm really not seeing what I'm missing.


Shouldn't you be using p.location.add()? location_set or <modelname>_set is the default name for the reverse lookup for that model.


location_set would be the default name for a backward relation, however since you've defined the ManyToManyField on the Person model, you can access the related manager via the field name:

p.location.add(l)

With this in mind, it makes more sense to name the ManyToManyField as a pluralised noun, e.g.

class Person(models.Model):
    first = models.CharField("First Name", max_length=50)
    [...]
    locations = models.ManyToManyField('Location')

Also, from memory, when you try to add model instances to a many-to-many relationship, the instance must be saved prior to adding.

0

精彩评论

暂无评论...
验证码 换一张
取 消