- 杂交(自定义第三张表+ManyToManyField)
# modles.py
class Boy(models.Model):
name = models.CharField(max_length=32)
class Girl(models.Model):
name = models.CharField(max_length=32)
m = models.ManyToManyField('Boy',through='Love',through_fields=('b','g')) # 只让其生成3张表,如果不加后面产生生成4张表
class Love(models.Model):
b = models.ForeignKey('Boy')
g = models.ForeignKey('Girl')
# views.py
def test(request):
obj = models.Girl.objects.filter(name='小于').first()
# obj.m.add(1) # 不行
# obj.m.remove(1) # 不行
# obj.m.set([1,2]) # 不行
# obj.m.clear() # 可以
# obj.m.all() # 可以
# 杂交的方法对获取查询方便点,还添加了清空功能
boy_obj = obj.m.all()
for i in boy_obj:
print(i.name)