1👍
✅
Not sure why you need 10 identical tables, let’s assume you have a good reason and just try to improve what you have. Why not just pass the model reference to methods so you don’t need to duplicate code just to change the model? Seems like you can accomplish the same thing with just the code below and if you need to change it you can change it in one place.
*Disclaimer: I am not familiar with the moz api and this code is not tested. There may be a problem with the __init__()
method of MozSerializer
such as missing params from the parent but at a minimum the mozs()
and moz()
methods should be sound.
def mozs():
models = [Url1, Url2, Url3, Url4, Url5, Url6, Url7, Url8, Url9, Url10]
for model in models:
moz(model)
def moz(model):
getids = model.objects.values_list('id', flat=True)
for id in getids:
if model.objects.get(id=id).pda == None:
a2 = model.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 = MozSerializer(data=authorities, model=model)
if serializer.is_valid():
serializer.save()
print "For %d we added %s" % (id, authorities)
print type(authorities)
class MozSerializer(serializers.Serializer):
pda = serializers.FloatField()
upa = serializers.FloatField()
def __init__(self, data=None, model=model):
self.model = model
self.keyword = serializers.PrimaryKeyRelatedField(queryset=model.objects.all())
super(MozSerializer, self).__init__(data=data)
def save(self):
keyword = self.validated_data['keyword']
pda = self.validated_data['pda']
upa = self.validated_data['upa']
self.model.objects.update(pda=pda, upa=upa)
Source:stackexchange.com