Я пытаюсь удалить дублирующийся код в моих моделях Django. Как видно из кода ниже, единственная разница между send_salary_notification
и send_pension_notifications
заключается в том, что одно использует связанное поле jurisdiction
, а другое - agency
. Как я могу изменить код так, чтобы юрисдикция / агентство были установлены один раз, исходя из record_type
?
Я попытался создать переменную класса как record_type
, и в этой первой функции установить переменную с cls.record_type = record_type
, а затем:
agencies_changed.append(subscription.record_type)
Но это дает ошибку, что record_type не является допустимым экземпляром.
Вот мой код:
class Subscriber(models.Model):
email = models.EmailField(null=False, unique=True)
activation_key = models.CharField(max_length=64)
key_expires = models.DateTimeField(default=get_key_expiration)
verified = models.BooleanField(default=False)
@classmethod
def send_notifications(cls, record_type, slugs):
"""
Sends notifications for all subscribers.
"""
subscribers = cls.objects.all()
for subscriber in subscribers:
if record_type == 'salary':
subscriber.send_salary_notifications(slugs, record_type)
elif record_type == 'pension':
subscriber.send_pension_notifications(slugs, record_type)
def send_salary_notifications(self, slugs, record_type):
matching_subscriptions = self.get_matching_salary_subscriptions(slugs)
agencies_changed = []
if not matching_subscriptions:
return None
for subscription in matching_subscriptions:
agencies_changed.append(subscription.jurisdiction)
self.update_salary_last_year_sent(subscription)
message = self.build_notification_message(agencies_changed, record_type)
self.send_notification_email(message)
def send_pension_notifications(self, slugs, record_type):
matching_subscriptions = self.get_matching_pension_subscriptions(slugs)
agencies_changed = []
if not matching_subscriptions:
return None
for subscription in matching_subscriptions:
agencies_changed.append(subscription.agency)
self.update_pension_last_year_sent(subscription)
message = self.build_notification_message(agencies_changed, record_type)
self.send_notification_email(message)
class SalarySubscription(models.Model):
subscriber = models.ForeignKey('subscriptions.Subscriber', related_name='salary_subscriptions')
jurisdiction = models.ForeignKey('jurisdiction.Jurisdiction')
last_year_sent = models.PositiveSmallIntegerField(null=True)
class PensionSubscription(models.Model):
subscriber = models.ForeignKey('subscriptions.Subscriber', related_name='pension_subscriptions')
agency = models.ForeignKey('pensions.Agency')
last_year_sent = models.PositiveSmallIntegerField(null=True)