我有10个模型(Urls1,Urls2,Urls3 ......)
每个看起来像这样:
class Url1(models.Model):
keyword = models.ForeignKey(KW)
url = models.URLField()
pda = models.FloatField(blank=True, null=True)
upa = models.FloatField(blank=True, null=True)
我的功能使用moz api将PDA / UPA结果拉到“url'字段。
这是前2的功能(其余8是相同的): 不考虑整个代码,下半部分与上半部相同,仅为第二个模型调整名称
def mozs():
getids1 = Url1.objects.values_list('id', flat=True)
for id in getids1:
if Url1.objects.get(id=id).pda == None:
a1 = Url1.objects.get(id=id).url
authorities = l.urlMetrics([a1], lsapi.UMCols.domainAuthority | lsapi.UMCols.pageAuthority)
authorities = str(authorities)
authorities = authorities.translate(None, '[]')
authorities = ast.literal_eval(authorities)
authorities['keyword'] = id
serializer = MozSerializer(data=authorities)
if serializer.is_valid():
serializer.save()
print "For %d we added %s" % (id, authorities)
print type(authorities)
getids2 = Url2.objects.values_list('id', flat=True)
for id in getids2:
if Url2.objects.get(id=id).pda == None:
a2 = Url2.objects.get(id=id).url
authorities = l.urlMetrics([a2], lsapi.UMCols.domainAuthority | lsapi.UMCols.pageAuthority)
authorities = str(authorities)
authorities = authorities.translate(None, '[]')
authorities = ast.literal_eval(authorities)
authorities['keyword'] = id
serializer = MozSerializer2(data=authorities)
if serializer.is_valid():
serializer.save()
print "For %d we added %s" % (id, authorities)
print type(authorities)
和序列化器(一半后同样的事情):
class MozSerializer(serializers.Serializer):
keyword = serializers.PrimaryKeyRelatedField(queryset=Url1.objects.all())
pda = serializers.FloatField()
upa = serializers.FloatField()
def save(self):
keyword = self.validated_data['keyword']
pda = self.validated_data['pda']
upa = self.validated_data['upa']
Url1.objects.update(pda=pda, upa=upa)
class MozSerializer2(serializers.Serializer):
keyword = serializers.PrimaryKeyRelatedField(queryset=Url2.objects.all())
pda = serializers.FloatField()
upa = serializers.FloatField()
def save(self):
keyword = self.validated_data['keyword']
pda = self.validated_data['pda']
upa = self.validated_data['upa']
Url2.objects.update(pda=pda, upa=upa)
这是我的第一个django项目,所以它可能充满了愚蠢的东西 - 欢迎任何改进建议:)
答案 0 :(得分:1)
不确定为什么你需要10个相同的表,让我们假设你有充分的理由,并试着改善你拥有的东西。为什么不将模型引用传递给方法,这样您就不需要重复代码只是为了更改模型?好像你可以用下面的代码完成同样的事情,如果你需要改变它,你可以在一个地方改变它。
*免责声明:我不熟悉moz api,此代码未经过测试。 __init__()
的{{1}}方法可能存在问题,例如父项缺少参数,但至少MozSerializer
和mozs()
方法应该是合理的。
moz()