1
0
mirror of https://github.com/ansible/awx.git synced 2024-10-31 15:21:13 +03:00

Remove the use of the deprecated Field.rel attribute

Also, rename a number of variables named `rel` for ease of searching.
This commit is contained in:
Jeff Bradberry 2019-06-17 11:13:18 -04:00
parent e0693d3746
commit bcbb768dd3
9 changed files with 41 additions and 64 deletions

View File

@ -401,21 +401,21 @@ class ListAPIView(generics.ListAPIView, GenericAPIView):
continue
if getattr(field, 'related_model', None):
fields.add('{}__search'.format(field.name))
for rel in self.model._meta.related_objects:
name = rel.related_name
if isinstance(rel, OneToOneRel) and self.model._meta.verbose_name.startswith('unified'):
for related in self.model._meta.related_objects:
name = related.related_name
if isinstance(related, OneToOneRel) and self.model._meta.verbose_name.startswith('unified'):
# Add underscores for polymorphic subclasses for user utility
name = rel.related_model._meta.verbose_name.replace(" ", "_")
name = related.related_model._meta.verbose_name.replace(" ", "_")
if skip_related_name(name) or name.endswith('+'):
continue
fields.add('{}__search'.format(name))
m2m_rel = []
m2m_rel += self.model._meta.local_many_to_many
m2m_related = []
m2m_related += self.model._meta.local_many_to_many
if issubclass(self.model, UnifiedJobTemplate) and self.model != UnifiedJobTemplate:
m2m_rel += UnifiedJobTemplate._meta.local_many_to_many
m2m_related += UnifiedJobTemplate._meta.local_many_to_many
if issubclass(self.model, UnifiedJob) and self.model != UnifiedJob:
m2m_rel += UnifiedJob._meta.local_many_to_many
for relationship in m2m_rel:
m2m_related += UnifiedJob._meta.local_many_to_many
for relationship in m2m_related:
if skip_related_name(relationship.name):
continue
if relationship.related_model._meta.app_label != 'main':

View File

@ -2560,7 +2560,7 @@ class CredentialSerializer(BaseSerializer):
def validate_credential_type(self, credential_type):
if self.instance and credential_type.pk != self.instance.credential_type.pk:
for rel in (
for related_objects in (
'ad_hoc_commands',
'insights_inventories',
'unifiedjobs',
@ -2569,7 +2569,7 @@ class CredentialSerializer(BaseSerializer):
'projectupdates',
'workflowjobnodes'
):
if getattr(self.instance, rel).count() > 0:
if getattr(self.instance, related_objects).count() > 0:
raise ValidationError(
_('You cannot change the credential type of the credential, as it may break the functionality'
' of the resources using it.'),
@ -4640,37 +4640,37 @@ class ActivityStreamSerializer(BaseSerializer):
return ""
def get_related(self, obj):
rel = {}
data = {}
if obj.actor is not None:
rel['actor'] = self.reverse('api:user_detail', kwargs={'pk': obj.actor.pk})
data['actor'] = self.reverse('api:user_detail', kwargs={'pk': obj.actor.pk})
for fk, __ in self._local_summarizable_fk_fields:
if not hasattr(obj, fk):
continue
m2m_list = self._get_rel(obj, fk)
m2m_list = self._get_related_objects(obj, fk)
if m2m_list:
rel[fk] = []
data[fk] = []
id_list = []
for thisItem in m2m_list:
if getattr(thisItem, 'id', None) in id_list:
for item in m2m_list:
if getattr(item, 'id', None) in id_list:
continue
id_list.append(getattr(thisItem, 'id', None))
if hasattr(thisItem, 'get_absolute_url'):
rel_url = thisItem.get_absolute_url(self.context.get('request'))
id_list.append(getattr(item, 'id', None))
if hasattr(item, 'get_absolute_url'):
url = item.get_absolute_url(self.context.get('request'))
else:
view_name = fk + '_detail'
rel_url = self.reverse('api:' + view_name, kwargs={'pk': thisItem.id})
rel[fk].append(rel_url)
url = self.reverse('api:' + view_name, kwargs={'pk': item.id})
data[fk].append(url)
if fk == 'schedule':
rel['unified_job_template'] = thisItem.unified_job_template.get_absolute_url(self.context.get('request'))
data['unified_job_template'] = item.unified_job_template.get_absolute_url(self.context.get('request'))
if obj.setting and obj.setting.get('category', None):
rel['setting'] = self.reverse(
data['setting'] = self.reverse(
'api:setting_singleton_detail',
kwargs={'category_slug': obj.setting['category']}
)
return rel
return data
def _get_rel(self, obj, fk):
def _get_related_objects(self, obj, fk):
related_model = ActivityStream._meta.get_field(fk).related_model
related_manager = getattr(obj, fk)
if issubclass(related_model, PolymorphicModel) and hasattr(obj, '_prefetched_objects_cache'):
@ -4703,7 +4703,7 @@ class ActivityStreamSerializer(BaseSerializer):
try:
if not hasattr(obj, fk):
continue
m2m_list = self._get_rel(obj, fk)
m2m_list = self._get_related_objects(obj, fk)
if m2m_list:
summary_fields[fk] = []
for thisItem in m2m_list:

View File

@ -2997,7 +2997,7 @@ class WorkflowJobTemplateNodeChildrenBaseList(EnforceParentRelationshipMixin, Su
relationships = ['success_nodes', 'failure_nodes', 'always_nodes']
relationships.remove(self.relationship)
qs = functools.reduce(lambda x, y: (x | y),
(Q(**{'{}__in'.format(rel): [sub.id]}) for rel in relationships))
(Q(**{'{}__in'.format(r): [sub.id]}) for r in relationships))
if models.WorkflowJobTemplateNode.objects.filter(Q(pk=parent.id) & qs).exists():
return {"Error": _("Relationship not allowed.")}

View File

@ -113,14 +113,9 @@ class AutoSingleRelatedObjectDescriptor(ReverseOneToOneDescriptor):
def __get__(self, instance, instance_type=None):
try:
return super(AutoSingleRelatedObjectDescriptor,
self).__get__(instance, instance_type)
return super(AutoSingleRelatedObjectDescriptor, self).__get__(instance, instance_type)
except self.related.related_model.DoesNotExist:
obj = self.related.related_model(**{self.related.field.name: instance})
if self.related.field.rel.parent_link:
raise NotImplementedError('not supported with polymorphic!')
for f in instance._meta.local_fields:
setattr(obj, f.name, getattr(instance, f.name))
obj.save()
return obj

View File

@ -62,24 +62,6 @@ from awx.main.models.oauth import ( # noqa
from oauth2_provider.models import Grant, RefreshToken # noqa -- needed django-oauth-toolkit model migrations
# Monkeypatch Django serializer to ignore django-taggit fields (which break
# the dumpdata command; see https://github.com/alex/django-taggit/issues/155).
from django.core.serializers.python import Serializer as _PythonSerializer
_original_handle_m2m_field = _PythonSerializer.handle_m2m_field
def _new_handle_m2m_field(self, obj, field):
try:
field.rel.through._meta
except AttributeError:
return
return _original_handle_m2m_field(self, obj, field)
_PythonSerializer.handle_m2m_field = _new_handle_m2m_field
# Add custom methods to User model for permissions checks.
from django.contrib.auth.models import User # noqa
from awx.main.access import ( # noqa

View File

@ -101,7 +101,7 @@ def test_instance_group_is_isolated(instance_group, isolated_instance_group):
assert not instance_group.is_isolated
assert isolated_instance_group.is_isolated
isolated_instance_group.instances = []
isolated_instance_group.instances.set([])
assert isolated_instance_group.is_isolated

View File

@ -208,7 +208,7 @@ def _check_unique_together_fields(model, ut):
field = model._meta.get_field(field_name)
if field_name == 'name':
has_name = True
elif type(field) == models.ForeignKey and field.rel.to != model:
elif type(field) == models.ForeignKey and field.related_model != model:
fk_names.append(field_name)
elif issubclass(type(field), models.CharField) and field.choices:
fields.append(field_name)
@ -256,7 +256,7 @@ def _dfs(configuration, model, graph, dead_ends, new_deadends, parents):
fields, fk_names = configuration[model][0][:], configuration[model][1][:]
adj_list = []
for fk_name in fk_names:
next_model = model._meta.get_field(fk_name).rel.to
next_model = model._meta.get_field(fk_name).related_model
if issubclass(next_model, ContentType):
continue
if next_model not in configuration or\

View File

@ -307,7 +307,7 @@ class SAMLAuth(BaseSAMLAuth):
return super(SAMLAuth, self).get_user(user_id)
def _update_m2m_from_groups(user, ldap_user, rel, opts, remove=True):
def _update_m2m_from_groups(user, ldap_user, related, opts, remove=True):
'''
Hepler function to update m2m relationship based on LDAP group membership.
'''
@ -328,10 +328,10 @@ def _update_m2m_from_groups(user, ldap_user, rel, opts, remove=True):
should_add = True
if should_add:
user.save()
rel.add(user)
elif remove and user in rel.all():
related.add(user)
elif remove and user in related.all():
user.save()
rel.remove(user)
related.remove(user)
@receiver(populate_user, dispatch_uid='populate-ldap-user')

View File

@ -50,7 +50,7 @@ def prevent_inactive_login(backend, details, user=None, *args, **kwargs):
raise AuthInactive(backend)
def _update_m2m_from_expression(user, rel, expr, remove=True):
def _update_m2m_from_expression(user, related, expr, remove=True):
'''
Helper function to update m2m relationship based on user matching one or
more expressions.
@ -73,12 +73,12 @@ def _update_m2m_from_expression(user, rel, expr, remove=True):
if ex.match(user.username) or ex.match(user.email):
should_add = True
if should_add:
rel.add(user)
related.add(user)
elif remove:
rel.remove(user)
related.remove(user)
def _update_org_from_attr(user, rel, attr, remove, remove_admins):
def _update_org_from_attr(user, related, attr, remove, remove_admins):
from awx.main.models import Organization
org_ids = []
@ -87,7 +87,7 @@ def _update_org_from_attr(user, rel, attr, remove, remove_admins):
org = Organization.objects.get_or_create(name=org_name)[0]
org_ids.append(org.id)
getattr(org, rel).members.add(user)
getattr(org, related).members.add(user)
if remove:
[o.member_role.members.remove(user) for o in