分表是非常常见的操作了。
定义需要分表操作的表:
class PhotosProxy(models.Model):
@classmethod
def get_sharding_model(cls, user_name=None):
class Meta:
db_table = 'Photos_%s' % user_name
attrs = {
'__module__': cls.__module__,
'__doc__': 'using Photos_%s table' % user_name,
'Meta': Meta
}
return type(str('Photos%s' % user_name), (cls, ), attrs)
id = models.AutoField(primary_key=True)
owner = models.CharField(max_length=20)
name = models.CharField(max_length=256)
创建新的分表:
new_N = PhotosProxy.get_sharding_model(user_name)
with connection.schema_editor() as schema_editor:
try:
schema_editor.create_model(new_N)
except:
print('exist')
print(new_N)
d0 = new_N()
d0.owner = user_name
new_N.save(d0)
查询数据:
Photos = PhotosProxy.get_sharding_model(owner)
userResult = Photos.objects.all()