标签:span mail phone manager oca forward any 重建 问题解决
表
class Books(models.Model): ‘‘‘书籍‘‘‘ id = models.AutoField(primary_key=True) name = models.CharField(verbose_name=‘书籍名‘, max_length=32)class Writer(models.Model): ‘‘‘作者‘‘‘ id = models.AutoField(primary_key=True) name = models.CharField(verbose_name=‘名字‘, max_length=32) Email = models.EmailField(verbose_name=‘邮件‘) phone = models.CharField(verbose_name=‘手机号‘, max_length=32) book = models.ManyToManyField(verbose_name=‘书籍‘, to=Books)
按照我们的理解
print(obj.book.name) None
问题解决
注意:要说明的是多对多的查询用.all,查单个的时候用.values或者values_list,不要用obj.book.name,这样查到的会是None,反向查询也是如此。
总结:不管是一对多,还是多对多,要是查询多得一方就得用all()
print(obj.book.values) <bound method BaseManager._get_queryset_methods.<locals>.create_method.<locals>.manager_method of <django.db.models.fields.related_descriptors.create_forward_many_to_many_manager.<locals>.ManyRelatedManager object at 0x03F8A950>> print(obj.book.values(‘name‘)) <QuerySet [{‘name‘: ‘鬼吹灯‘}, {‘name‘: ‘择天记‘}, {‘name‘: ‘大主宰‘}, {‘name‘: ‘名族的重建‘}]>
标签:span mail phone manager oca forward any 重建 问题解决
原文地址:https://www.cnblogs.com/HByang/p/12376770.html