diff --git a/python/nav/alertengine/base.py b/python/nav/alertengine/base.py index 644f3d1629..0bbc28be19 100644 --- a/python/nav/alertengine/base.py +++ b/python/nav/alertengine/base.py @@ -70,7 +70,7 @@ def check_alerts(debug=False): now = datetime.now() # Get all alerts that aren't in alert queue due to subscription - new_alerts = AlertQueue.objects.filter(accountalertqueue__isnull=True) + new_alerts = AlertQueue.objects.filter(queued_alerts__isnull=True) num_new_alerts = len(new_alerts) initial_alerts = AlertQueue.objects.values_list('id', flat=True) @@ -180,9 +180,9 @@ def subscription_sort_key(subscription): return subscription.type # Build datastructure that contains accounts and corresponding - # filtergroupcontent_set so that we don't redo db queries to much + # filter_group_contents so that we don't redo db queries to much for account in Account.objects.filter( - alertpreference__active_profile__isnull=False + alert_preference__active_profile__isnull=False ): profile = account.get_active_profile() time_period = profile.get_active_timeperiod() if profile else None @@ -191,7 +191,7 @@ def subscription_sort_key(subscription): continue current_alertsubscriptions = sorted( - time_period.alertsubscription_set.all(), key=subscription_sort_key + time_period.alert_subscriptions.all(), key=subscription_sort_key ) tmp = [] @@ -199,7 +199,7 @@ def subscription_sort_key(subscription): tmp.append( ( alertsubscription, - alertsubscription.filter_group.filtergroupcontent_set.all(), + alertsubscription.filter_group.filter_group_contents.all(), ) ) @@ -208,7 +208,7 @@ def subscription_sort_key(subscription): for filtergroup in FilterGroup.objects.filter( group_permissions__accounts__in=[account] ): - permissions.append(filtergroup.filtergroupcontent_set.all()) + permissions.append(filtergroup.filter_group_contents.all()) accounts.append((account, tmp, permissions)) del permissions @@ -415,7 +415,7 @@ def process_single_queued_notification(queued_alert, now): ) try: - subscription.time_period.profile.alertpreference + subscription.time_period.profile.alert_preference except AlertPreference.DoesNotExist: subscription = None @@ -474,7 +474,7 @@ def _verify_daily_dispatch(queued_alert, now, _logger=_logger): subscription = queued_alert.subscription daily_time = subscription.time_period.profile.daily_dispatch_time last_sent = ( - subscription.time_period.profile.alertpreference.last_sent_day or datetime.min + subscription.time_period.profile.alert_preference.last_sent_day or datetime.min ) # If the last sent date is less than the current date, and we are # past the daily time and the alert was added to the queue before @@ -498,7 +498,7 @@ def _verify_weekly_dispatch(queued_alert, now, _logger=_logger): weekly_time = subscription.time_period.profile.weekly_dispatch_time weekly_day = subscription.time_period.profile.weekly_dispatch_day last_sent = ( - subscription.time_period.profile.alertpreference.last_sent_week or datetime.min + subscription.time_period.profile.alert_preference.last_sent_week or datetime.min ) # Check that we are at the correct weekday, and that the last sent @@ -562,7 +562,7 @@ def _get_number_of_timeperiods_today(alertprofile, now): valid_during = [TimePeriod.ALL_WEEK, TimePeriod.WEEKENDS] else: valid_during = [TimePeriod.ALL_WEEK, TimePeriod.WEEKDAYS] - return alertprofile.timeperiod_set.filter(valid_during__in=valid_during).count() + return alertprofile.time_periods.filter(valid_during__in=valid_during).count() def _calculate_timeperiod_start(timeperiod, now=None): diff --git a/python/nav/django/utils.py b/python/nav/django/utils.py index 25fdbefabb..7b21113f7b 100644 --- a/python/nav/django/utils.py +++ b/python/nav/django/utils.py @@ -44,7 +44,7 @@ def get_account(request): def is_admin(account): """Check if user is a member of the administrator group""" - return account.accountgroup_set.filter(pk=AccountGroup.ADMIN_GROUP).count() > 0 + return account.groups.filter(pk=AccountGroup.ADMIN_GROUP).count() > 0 def get_verbose_name(model, lookup): diff --git a/python/nav/models/profiles.py b/python/nav/models/profiles.py index cd460ab2be..8b4d4106a4 100644 --- a/python/nav/models/profiles.py +++ b/python/nav/models/profiles.py @@ -105,7 +105,10 @@ class Account(models.Model): preferences = HStoreField(default=dict) organizations = models.ManyToManyField( - Organization, db_table='accountorg', blank=True + Organization, + db_table='accountorg', + blank=True, + related_name="accounts", ) # Set this in order to provide a link to the actual operator when Account @@ -125,7 +128,7 @@ def __str__(self): def get_active_profile(self): """Returns the account's active alert profile""" try: - return self.alertpreference.active_profile + return self.alert_preference.active_profile except (AlertPreference.DoesNotExist, AlertProfile.DoesNotExist): pass @@ -136,7 +139,7 @@ def get_groups(self): try: return self._cached_groups except AttributeError: - self._cached_groups = self.accountgroup_set.values_list('id', flat=True) + self._cached_groups = self.groups.values_list('id', flat=True) return self._cached_groups def get_privileges(self): @@ -155,7 +158,7 @@ def get_tools(self): """Get the tool list for this account""" return [ tool - for tool in self.accounttool_set.all().order_by('priority') + for tool in self.account_tools.all().order_by('priority') if self.has_perm('web_access', tool.tool.uri) ] @@ -297,7 +300,7 @@ def unlocked_password(self): return self.password[1:] if self.password else '' def get_email_addresses(self): - return self.alertaddress_set.filter(type__name=AlertSender.EMAIL) + return self.alert_addresses.filter(type__name=AlertSender.EMAIL) class AccountGroup(models.Model): @@ -312,7 +315,10 @@ class AccountGroup(models.Model): name = VarcharField() description = VarcharField(db_column='descr') # FIXME this uses a view hack, was AccountInGroup - accounts = models.ManyToManyField('Account') + accounts = models.ManyToManyField( + 'Account', + related_name="groups", + ) class Meta(object): db_table = u'accountgroup' @@ -342,7 +348,10 @@ class NavbarLink(models.Model): """A hyperlink on a user's navigation bar.""" account = models.ForeignKey( - 'Account', on_delete=models.CASCADE, db_column='accountid' + 'Account', + on_delete=models.CASCADE, + db_column='accountid', + related_name="navbar_links", ) name = models.CharField('Link text', blank=False, max_length=100) uri = models.CharField('URL', blank=False, max_length=100) @@ -359,10 +368,16 @@ class Privilege(models.Model): """A privilege granted to an AccountGroup.""" group = models.ForeignKey( - 'AccountGroup', on_delete=models.CASCADE, db_column='accountgroupid' + 'AccountGroup', + on_delete=models.CASCADE, + db_column='accountgroupid', + related_name="privileges", ) type = models.ForeignKey( - 'PrivilegeType', on_delete=models.CASCADE, db_column='privilegeid' + 'PrivilegeType', + on_delete=models.CASCADE, + db_column='privilegeid', + related_name="privileges", ) target = VarcharField() @@ -395,9 +410,17 @@ class AlertAddress(models.Model): DEBUG_MODE = False account = models.ForeignKey( - 'Account', on_delete=models.CASCADE, db_column='accountid' + 'Account', + on_delete=models.CASCADE, + db_column='accountid', + related_name="alert_addresses", + ) + type = models.ForeignKey( + 'AlertSender', + on_delete=models.CASCADE, + db_column='type', + related_name="alert_addresses", ) - type = models.ForeignKey('AlertSender', on_delete=models.CASCADE, db_column='type') address = VarcharField() class Meta(object): @@ -556,10 +579,18 @@ class AlertPreference(models.Model): """AlertProfile account preferences""" account = models.OneToOneField( - 'Account', primary_key=True, on_delete=models.CASCADE, db_column='accountid' + 'Account', + primary_key=True, + on_delete=models.CASCADE, + db_column='accountid', + related_name="alert_preference", ) active_profile = models.OneToOneField( - 'AlertProfile', on_delete=models.CASCADE, db_column='activeprofile', null=True + 'AlertProfile', + on_delete=models.CASCADE, + db_column='activeprofile', + null=True, + related_name="alert_preference", ) last_sent_day = models.DateTimeField(db_column='lastsentday') last_sent_week = models.DateTimeField(db_column='lastsentweek') @@ -598,7 +629,10 @@ class AlertProfile(models.Model): ) account = models.ForeignKey( - 'Account', on_delete=models.CASCADE, db_column='accountid' + 'Account', + on_delete=models.CASCADE, + db_column='accountid', + related_name="alert_profiles", ) name = VarcharField() daily_dispatch_time = models.TimeField(default='08:00') @@ -631,7 +665,7 @@ def get_active_timeperiod(self): # The following code should get the currently active timeperiod. active_timeperiod = None timeperiods = list( - self.timeperiod_set.filter(valid_during__in=valid_during).order_by('start') + self.time_periods.filter(valid_during__in=valid_during).order_by('start') ) # If the current time is before the start of the first time # period, the active time period is the last one (i.e. from @@ -670,7 +704,10 @@ class TimePeriod(models.Model): ) profile = models.ForeignKey( - 'AlertProfile', on_delete=models.CASCADE, db_column='alert_profile_id' + 'AlertProfile', + on_delete=models.CASCADE, + db_column='alert_profile_id', + related_name="time_periods", ) start = models.TimeField(db_column='start_time', default='08:00') valid_during = models.IntegerField(choices=VALID_DURING_CHOICES, default=ALL_WEEK) @@ -707,14 +744,17 @@ class AlertSubscription(models.Model): alert_address = models.ForeignKey( 'AlertAddress', on_delete=models.CASCADE, + related_name="alert_subscriptions", ) time_period = models.ForeignKey( 'TimePeriod', on_delete=models.CASCADE, + related_name="alert_subscriptions", ) filter_group = models.ForeignKey( 'FilterGroup', on_delete=models.CASCADE, + related_name="alert_subscriptions", ) type = models.IntegerField( db_column='subscription_type', choices=SUBSCRIPTION_TYPES, default=NOW @@ -725,7 +765,7 @@ class Meta(object): db_table = u'alertsubscription' def delete(self): - for a in self.accountalertqueue_set.all(): + for a in self.queued_alerts.all(): a.delete() super(AlertSubscription, self).delete() @@ -767,10 +807,12 @@ class FilterGroupContent(models.Model): filter = models.ForeignKey( 'Filter', on_delete=models.CASCADE, + related_name="filter_group_contents", ) filter_group = models.ForeignKey( 'FilterGroup', on_delete=models.CASCADE, + related_name="filter_group_contents", ) class Meta(object): @@ -862,6 +904,7 @@ class Operator(models.Model): match_field = models.ForeignKey( 'MatchField', on_delete=models.CASCADE, + related_name="operators", ) class Meta(object): @@ -889,10 +932,12 @@ class Expression(models.Model): filter = models.ForeignKey( 'Filter', on_delete=models.CASCADE, + related_name="expressions", ) match_field = models.ForeignKey( 'MatchField', on_delete=models.CASCADE, + related_name="expressions", ) operator = models.IntegerField(choices=Operator.OPERATOR_TYPES) value = VarcharField() @@ -918,7 +963,12 @@ class Filter(models.Model): Handles the actual construction of queries to be run taking into account special cases like the IP datatype and WILDCARD lookups.""" - owner = models.ForeignKey('Account', on_delete=models.CASCADE, null=True) + owner = models.ForeignKey( + 'Account', + on_delete=models.CASCADE, + null=True, + related_name="filters", + ) name = VarcharField() class Meta(object): @@ -945,7 +995,7 @@ def verify(self, alert): exclude = {} extra = {'where': [], 'params': []} - for expression in self.expression_set.all(): + for expression in self.expressions.all(): # Handle IP datatypes: if expression.match_field.data_type == MatchField.IP: # Trick the ORM into joining the tables we want @@ -1042,12 +1092,19 @@ class FilterGroup(models.Model): """ - owner = models.ForeignKey('Account', on_delete=models.CASCADE, null=True) + owner = models.ForeignKey( + 'Account', + on_delete=models.CASCADE, + null=True, + related_name="filter_groups", + ) name = VarcharField() description = VarcharField() group_permissions = models.ManyToManyField( - 'AccountGroup', db_table='filtergroup_group_permission' + 'AccountGroup', + db_table='filtergroup_group_permission', + related_name="filter_groups", ) class Meta(object): @@ -1271,7 +1328,11 @@ class SMSQueue(models.Model): ) account = models.ForeignKey( - 'Account', on_delete=models.CASCADE, db_column='accountid', null=True + 'Account', + on_delete=models.CASCADE, + db_column='accountid', + null=True, + related_name="sms_queues", ) time = models.DateTimeField(auto_now_add=True) phone = models.CharField(max_length=15) @@ -1298,11 +1359,24 @@ def save(self, *args, **kwargs): class AccountAlertQueue(models.Model): """Defines which alerts should be keept around and sent at a later time""" - account = models.ForeignKey('Account', on_delete=models.CASCADE, null=True) + account = models.ForeignKey( + 'Account', + on_delete=models.CASCADE, + null=True, + related_name="queued_alerts", + ) subscription = models.ForeignKey( - 'AlertSubscription', on_delete=models.CASCADE, null=True + 'AlertSubscription', + on_delete=models.CASCADE, + null=True, + related_name="queued_alerts", + ) + alert = models.ForeignKey( + 'AlertQueue', + on_delete=models.CASCADE, + null=True, + related_name="queued_alerts", ) - alert = models.ForeignKey('AlertQueue', on_delete=models.CASCADE, null=True) insertion_time = models.DateTimeField(auto_now_add=True) class Meta(object): @@ -1321,7 +1395,7 @@ def delete(self, *args, **kwargs): # Remove the alert from the AlertQueue if we are the last item # depending upon it. - if self.alert.accountalertqueue_set.count() == 0: + if self.alert.queued_alerts.count() == 0: self.alert.delete() def send(self): @@ -1376,7 +1450,12 @@ class NetmapView(models.Model): """Properties for a specific view in Netmap""" viewid = models.AutoField(primary_key=True) - owner = models.ForeignKey(Account, on_delete=models.CASCADE, db_column='owner') + owner = models.ForeignKey( + Account, + on_delete=models.CASCADE, + db_column='owner', + related_name="netmap_views", + ) title = models.TextField() description = models.TextField(null=True, blank=True) topology = models.IntegerField(choices=LINK_TYPES) @@ -1412,8 +1491,18 @@ class NetmapViewDefaultView(models.Model): """Default view for each user""" id = models.AutoField(primary_key=True) - view = models.ForeignKey(NetmapView, on_delete=models.CASCADE, db_column='viewid') - owner = models.ForeignKey(Account, on_delete=models.CASCADE, db_column='ownerid') + view = models.ForeignKey( + NetmapView, + on_delete=models.CASCADE, + db_column='viewid', + related_name="default_views", + ) + owner = models.ForeignKey( + Account, + on_delete=models.CASCADE, + db_column='ownerid', + related_name="default_views", + ) class Meta(object): db_table = u'netmap_view_defaultview' @@ -1432,13 +1521,13 @@ class NetmapViewCategories(models.Model): NetmapView, on_delete=models.CASCADE, db_column='viewid', - related_name='categories_set', + related_name='netmap_view_categories', ) category = models.ForeignKey( Category, on_delete=models.CASCADE, db_column='catid', - related_name='netmapview_set', + related_name='netmap_view_categories', ) def __str__(self): @@ -1457,13 +1546,13 @@ class NetmapViewNodePosition(models.Model): NetmapView, on_delete=models.CASCADE, db_column='viewid', - related_name='node_position_set', + related_name='node_positions', ) netbox = models.ForeignKey( Netbox, on_delete=models.CASCADE, db_column='netboxid', - related_name='node_position_set', + related_name='node_positions', ) x = models.IntegerField() y = models.IntegerField() @@ -1478,7 +1567,10 @@ class AccountTool(models.Model): id = models.AutoField(primary_key=True, db_column='account_tool_id') toolname = VarcharField() account = models.ForeignKey( - Account, on_delete=models.CASCADE, db_column='accountid' + Account, + on_delete=models.CASCADE, + db_column='accountid', + related_name="account_tools", ) display = models.BooleanField(default=True) priority = models.IntegerField(default=0) @@ -1499,6 +1591,7 @@ class AccountDashboard(models.Model): account = models.ForeignKey( Account, on_delete=models.CASCADE, + related_name="account_dashboards", ) def __str__(self): @@ -1529,11 +1622,18 @@ class AccountNavlet(models.Model): navlet = VarcharField() order = models.IntegerField(default=0, db_column='displayorder') - account = models.ForeignKey(Account, on_delete=models.CASCADE, db_column='account') + account = models.ForeignKey( + Account, + on_delete=models.CASCADE, + db_column='account', + related_name="widgets", + ) preferences = DictAsJsonField(null=True) column = models.IntegerField(db_column='col') dashboard = models.ForeignKey( - AccountDashboard, on_delete=models.CASCADE, related_name='widgets' + AccountDashboard, + on_delete=models.CASCADE, + related_name='widgets', ) def __str__(self): @@ -1567,6 +1667,7 @@ class ReportSubscription(models.Model): account = models.ForeignKey( Account, on_delete=models.CASCADE, + related_name="report_subscriptions", ) address = models.ForeignKey( AlertAddress, diff --git a/python/nav/web/alertprofiles/forms.py b/python/nav/web/alertprofiles/forms.py index 8a85f50da1..319cf4ac88 100644 --- a/python/nav/web/alertprofiles/forms.py +++ b/python/nav/web/alertprofiles/forms.py @@ -546,7 +546,7 @@ def __init__(self, *args, **kwargs): if isinstance(match_field, MatchField): # Get all operators and make a choice field - operators = match_field.operator_set.all() + operators = match_field.operators.all() self.fields['operator'] = forms.models.ChoiceField( choices=[(o.type, o) for o in operators] ) diff --git a/python/nav/web/alertprofiles/utils.py b/python/nav/web/alertprofiles/utils.py index a53fc72f32..f988836c7a 100644 --- a/python/nav/web/alertprofiles/utils.py +++ b/python/nav/web/alertprofiles/utils.py @@ -45,7 +45,7 @@ def account_owns_filters(account, *filters): """ # Check if user is admin - groups = account.accountgroup_set.filter(pk=ADMINGROUP).count() + groups = account.groups.filter(pk=ADMINGROUP).count() if groups > 0: # User is admin return True diff --git a/python/nav/web/alertprofiles/views.py b/python/nav/web/alertprofiles/views.py index 829aba4a02..30956bf079 100644 --- a/python/nav/web/alertprofiles/views.py +++ b/python/nav/web/alertprofiles/views.py @@ -82,7 +82,7 @@ def overview(request): account = get_account(request) # Get information about user - groups = account.accountgroup_set.all() + groups = account.groups.all() try: active_profile = account.get_active_profile() except ObjectDoesNotExist: @@ -131,7 +131,7 @@ def show_profile(request): order_by = 'name' try: - active_profile = account.alertpreference.active_profile + active_profile = account.alert_preference.active_profile except Exception: active_profile = None @@ -1475,7 +1475,9 @@ def filter_remove(request): } ) - filter_groups = FilterGroup.objects.filter(filtergroupcontent__filter=filtr) + filter_groups = FilterGroup.objects.filter( + filter_group_contents__filter=filtr + ) for fgroup in filter_groups: warnings.append( { @@ -1783,7 +1785,7 @@ def filter_group_show_form(request, filter_group_id=None, filter_group_form=None page_name = filter_group.name profiles = AlertProfile.objects.filter( - timeperiod__alertsubscription__filter_group=filter_group + time_periods__alert_subscriptions__filter_group=filter_group ).distinct() if profiles: names = ', '.join([p.name for p in profiles]) @@ -1928,7 +1930,7 @@ def filter_group_remove(request): for fgroup in filter_groups: subscriptions = AlertSubscription.objects.filter(filter_group=fgroup) time_periods = TimePeriod.objects.filter( - alertsubscription__in=subscriptions + alert_subscriptions__in=subscriptions ) profiles = AlertProfile.objects.filter(timeperiod__in=time_periods) warnings = [] @@ -2308,13 +2310,13 @@ def matchfield_show_form(request, matchfield_id=None, matchfield_form=None): if not matchfield_form: matchfield_form = MatchFieldForm(instance=matchfield) matchfield_operators_id = [ - m_operator.type for m_operator in matchfield.operator_set.all() + m_operator.type for m_operator in matchfield.operators.all() ] page_name = matchfield.name expressions = Expression.objects.filter(match_field=matchfield) - filters = Filter.objects.filter(expression__in=expressions) + filters = Filter.objects.filter(expressions__in=expressions) if filters: names = ', '.join([f.name for f in filters]) @@ -2398,8 +2400,8 @@ def matchfield_save(request): operators = [] for oper in request.POST.getlist('operator'): operators.append(Operator(type=int(oper), match_field=matchfield)) - matchfield.operator_set.all().delete() - matchfield.operator_set.add(*operators) + matchfield.operators.all().delete() + matchfield.operators.add(*operators) new_message( request, @@ -2431,7 +2433,7 @@ def matchfield_remove(request): ) return HttpResponseRedirect(reverse('alertprofiles-matchfields')) else: - matchfields = MatchField.objects.prefetch_related('expression_set').filter( + matchfields = MatchField.objects.prefetch_related('expressions').filter( pk__in=request.POST.getlist('matchfield') ) @@ -2441,7 +2443,7 @@ def matchfield_remove(request): elements = [] for match_field in matchfields: - expressions = match_field.expression_set.all() + expressions = match_field.expressions.all() warnings = [] for expr in expressions: warnings.append( @@ -2512,7 +2514,7 @@ def permission_list(request, group_id=None): request, _('Requested account group does not exist.') ) - permissions = AccountGroup.objects.get(pk=group_id).filtergroup_set.all() + permissions = AccountGroup.objects.get(pk=group_id).filter_groups.all() active = {'permissions': True} info_dict = { @@ -2551,7 +2553,7 @@ def permissions_save(request): pk__in=request.POST.getlist('filter_group') ) - group.filtergroup_set.set(filter_groups) + group.filter_groups.set(filter_groups) new_message( request, diff --git a/python/nav/web/api/v1/serializers.py b/python/nav/web/api/v1/serializers.py index 7001e0fc62..be3c35a6d1 100644 --- a/python/nav/web/api/v1/serializers.py +++ b/python/nav/web/api/v1/serializers.py @@ -39,7 +39,7 @@ class AccountSerializer(serializers.ModelSerializer): """Serializer for accounts""" accountgroups = serializers.PrimaryKeyRelatedField( - source='accountgroup_set', + source='groups', many=True, queryset=profiles.AccountGroup.objects.all(), ) diff --git a/python/nav/web/auth.py b/python/nav/web/auth.py index 342a5f7fdd..e3332e61da 100644 --- a/python/nav/web/auth.py +++ b/python/nav/web/auth.py @@ -161,9 +161,9 @@ def _handle_ldap_admin_status(ldap_user, nav_account): if is_admin is not None: admin_group = AccountGroup.objects.get(id=AccountGroup.ADMIN_GROUP) if is_admin: - nav_account.accountgroup_set.add(admin_group) + nav_account.groups.add(admin_group) else: - nav_account.accountgroup_set.remove(admin_group) + nav_account.groups.remove(admin_group) def authenticate_remote_user(request): diff --git a/python/nav/web/netmap/serializers.py b/python/nav/web/netmap/serializers.py index 36693b5106..a4a25c8995 100644 --- a/python/nav/web/netmap/serializers.py +++ b/python/nav/web/netmap/serializers.py @@ -114,7 +114,7 @@ def _update_categories(instance, new_categories): del_categories = old_categories - new_categories # Delete removed categories - instance.categories_set.filter(category__in=del_categories).delete() + instance.netmap_view_categories.filter(category__in=del_categories).delete() # Create added categories profiles.NetmapViewCategories.objects.bulk_create( diff --git a/python/nav/web/templates/business/frag-report-items.html b/python/nav/web/templates/business/frag-report-items.html index 6df17be692..fa0c0ae0ee 100644 --- a/python/nav/web/templates/business/frag-report-items.html +++ b/python/nav/web/templates/business/frag-report-items.html @@ -1,4 +1,4 @@ -{% for subscription in request.account.reportsubscription_set.all %} +{% for subscription in request.account.report_subscriptions.all %}
  • {{ subscription }}