1
0
mirror of https://github.com/ansible/awx.git synced 2024-10-31 23:51:09 +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 continue
if getattr(field, 'related_model', None): if getattr(field, 'related_model', None):
fields.add('{}__search'.format(field.name)) fields.add('{}__search'.format(field.name))
for rel in self.model._meta.related_objects: for related in self.model._meta.related_objects:
name = rel.related_name name = related.related_name
if isinstance(rel, OneToOneRel) and self.model._meta.verbose_name.startswith('unified'): if isinstance(related, OneToOneRel) and self.model._meta.verbose_name.startswith('unified'):
# Add underscores for polymorphic subclasses for user utility # 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('+'): if skip_related_name(name) or name.endswith('+'):
continue continue
fields.add('{}__search'.format(name)) fields.add('{}__search'.format(name))
m2m_rel = [] m2m_related = []
m2m_rel += self.model._meta.local_many_to_many m2m_related += self.model._meta.local_many_to_many
if issubclass(self.model, UnifiedJobTemplate) and self.model != UnifiedJobTemplate: 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: if issubclass(self.model, UnifiedJob) and self.model != UnifiedJob:
m2m_rel += UnifiedJob._meta.local_many_to_many m2m_related += UnifiedJob._meta.local_many_to_many
for relationship in m2m_rel: for relationship in m2m_related:
if skip_related_name(relationship.name): if skip_related_name(relationship.name):
continue continue
if relationship.related_model._meta.app_label != 'main': if relationship.related_model._meta.app_label != 'main':

View File

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

View File

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

View File

@ -113,14 +113,9 @@ class AutoSingleRelatedObjectDescriptor(ReverseOneToOneDescriptor):
def __get__(self, instance, instance_type=None): def __get__(self, instance, instance_type=None):
try: try:
return super(AutoSingleRelatedObjectDescriptor, return super(AutoSingleRelatedObjectDescriptor, self).__get__(instance, instance_type)
self).__get__(instance, instance_type)
except self.related.related_model.DoesNotExist: except self.related.related_model.DoesNotExist:
obj = self.related.related_model(**{self.related.field.name: instance}) 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() obj.save()
return obj 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 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. # Add custom methods to User model for permissions checks.
from django.contrib.auth.models import User # noqa from django.contrib.auth.models import User # noqa
from awx.main.access import ( # 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 not instance_group.is_isolated
assert isolated_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 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) field = model._meta.get_field(field_name)
if field_name == 'name': if field_name == 'name':
has_name = True 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) fk_names.append(field_name)
elif issubclass(type(field), models.CharField) and field.choices: elif issubclass(type(field), models.CharField) and field.choices:
fields.append(field_name) 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][:] fields, fk_names = configuration[model][0][:], configuration[model][1][:]
adj_list = [] adj_list = []
for fk_name in fk_names: 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): if issubclass(next_model, ContentType):
continue continue
if next_model not in configuration or\ if next_model not in configuration or\

View File

@ -307,7 +307,7 @@ class SAMLAuth(BaseSAMLAuth):
return super(SAMLAuth, self).get_user(user_id) 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. 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 should_add = True
if should_add: if should_add:
user.save() user.save()
rel.add(user) related.add(user)
elif remove and user in rel.all(): elif remove and user in related.all():
user.save() user.save()
rel.remove(user) related.remove(user)
@receiver(populate_user, dispatch_uid='populate-ldap-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) 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 Helper function to update m2m relationship based on user matching one or
more expressions. 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): if ex.match(user.username) or ex.match(user.email):
should_add = True should_add = True
if should_add: if should_add:
rel.add(user) related.add(user)
elif remove: 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 from awx.main.models import Organization
org_ids = [] 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 = Organization.objects.get_or_create(name=org_name)[0]
org_ids.append(org.id) org_ids.append(org.id)
getattr(org, rel).members.add(user) getattr(org, related).members.add(user)
if remove: if remove:
[o.member_role.members.remove(user) for o in [o.member_role.members.remove(user) for o in