django 数据库模型 多对多
创建数据库模型
class ShopKeeper(models.Model):#商店
username = models.CharField(max_length=10,primary_key=True)
name = models.CharField(max_length=10)
password = models.CharField(max_length=10)
class Meta:
db_table = 'shopkeeper'
class Commodity(models.Model):#商品
name = models.CharField(max_length=20)
price = models.DecimalField(max_digits=10,decimal_places=2)
img = models.CharField(max_length=50)
f = models.ManyToManyField("ShopKeeper")
class Meta:
db_table = 'commodity'
查询
正向查询
first = Commodity.objects.get(name='苹果')
first.f.all()
反向查询
first = ShopKeeper.objects.filter(username='11111111').first()#必须是唯一的,结果不能是一个查询集合,如果字段是唯一的可以使用get(username='11111111')代替filter(username='11111111').first()
first.commodity_set.all()
添加
first = Commodity.objects.create(name='香蕉',price=20.0,img='VCG21400475931.jpg')
first.f.add('11111111')#add中是ShopKeeper的主键
#添加多条数据
first.f.add(*[1,2,3])
first = ShopKeeper.objects.create(username='11111113',name='店主C',password='00000000')
first.commodity_set.add(1)#add中是commodity表的主键
修改
first = Commodity.objects.get(id=1)
first.f.set(['11111111','11111112','11111113'])
first = ShopKeeper.objects.get(username='11111113')
first.commodity_set.set([1,2,3])
删除
first = ShopKeeper.objects.get(username='11111113')
first.commodity_set.clear() #清除所有与username='11111113'相关联的数据
first.commodity_set.remove(1) #删除 username='11111113' id=1