DJango-ORM根据primary_value获取对应的类对象
@classmethod
def get_obj_by_primary_value(cls, primary_value=None):
primary_key = None
fields = cls._meta.get_fields()
for obj in fields:
if obj.primary_key:
primary_key = obj.name
param_dic = {
primary_key: primary_value
}
data = cls.objects.filter(**param_dic).first()
return data
需要解决两点
1.找到主键属性
2.如果重写过滤条件
好用的例子,
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import time from jsonfield import JSONField from django.db.models import ( CharField, ) from django.db import models class OpsThread(models.Model): name = CharField(max_length=255, primary_key=True, verbose_name="线程名字") config = JSONField(verbose_name="线程配置", null=True, blank=True) create_time = CharField(verbose_name="创建时间", max_length=50, default=str(int(round(time.time() * 1000)))) update_time = CharField(verbose_name="更新时间", max_length=50, default=str(int(round(time.time() * 1000)))) class Meta: managed = True verbose_name = "Thread表" db_table = "ops_thread" # ###############################复制以下代码############## @classmethod def _get_primary_key(cls): primary_key = None fields = cls._meta.get_fields() for obj in fields: if obj.primary_key: primary_key = obj.name return primary_key @classmethod def save_or_update(cls, param_dic): primary_key = cls._get_primary_key() # 先查询 然后再更新或者保存 primary_value = param_dic.get(primary_key) primary_dic = { primary_key: primary_value } obj = cls.objects.filter(**primary_dic) if obj: obj.update(**param_dic) else: cls.objects.create(**param_dic) if __name__ == '__main__': param_dic = { "name": "Thread-1" # 调用的时候自己写主键,这个前端会传过来 } thread_obj = OpsThread.save_or_update(param_dic=param_dic)
-----------------------------------------------------------------------------------------------------------------------------------------