下記code記載しますが、現状 モデルが3つあります。(user、shop_name、schedule)
shop_nameはOneToOneでuserに紐づいており、scheduleもOneToOneでuserに紐づいています。
ちなみにuserとshop_nameは同じアプリ内のモデル、scheduleは別のアプリのモデルとなってます。
やりたいこと
scheduleはカレンダーみたいになっており、各userがカレンダーを持っています。
全てのユーザーのカレンダーを表示することは出来たのですが、このカレンダーをshop_nameごとに分けて表示をさせたいです。
register.models.py class CustomUserManager(UserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **extra_fields) class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) first_name = models.CharField(_('first name'), max_length=30, blank=True) last_name = models.CharField(_('last name'), max_length=150, blank=True) is_staff = models.BooleanField( _('staff status'), default=False, help_text=_( 'Designates whether the user can log into this admin site.'), ) is_active = models.BooleanField( _('active'), default=True, help_text=_( 'Designates whether this user should be treated as active. ' 'Unselect this instead of deleting accounts.' ), ) date_joined = models.DateTimeField(_('date joined'), default=timezone.now) objects = CustomUserManager() EMAIL_FIELD = 'email' USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] class Meta: verbose_name = _('user') verbose_name_plural = _('users') def email_user(self, subject, message, from_email=None, **kwargs): """Send an email to this user.""" send_mail(subject, message, from_email, [self.email], **kwargs) @property def username(self): return self.email class Shop_name(models.Model): SHOP_CHOICES = ( ('1', 'A'), ('2', 'B'), ('3', 'C'), ('4', 'D'), ('5', 'E'),) shop = models.CharField("店舗", max_length=3,choices=SHOP_CHOICES, blank=True,default=1) date_of_birth = models.DateField("生年月日",blank=True,default=datetime(1999, 1, 1)) start_day = models.DateField("入店日",blank=True,default=datetime(1999, 1, 1)) user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) def __str__(self): return self.shop
app.models.py SUB_START = ( ('0', '✕'), ('1', '14'), ('2', '16'), ('3', '17'), ('4', '17.5'), ('5', '18'), ('6', '18.5'), ('7', '19'), ('8', '19.5'), ('9', '20'), ('10', '〇'), ) SUB_END = ( ('0', '✕'), ('1', '22'), ('2', '23'), ('3', '〇'), ) class Schedule(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name='ユーザー', on_delete=models.SET_NULL, blank=True, null=True) start_time = models.CharField('開始時間', choices= SUB_START, max_length=50,blank=True,default="0") end_time = models.CharField('終了時間', choices= SUB_END, max_length=50,blank=True,default="0") date = models.DateField('日付') # created_at = models.DateTimeField('作成日', default=timezone.now) objects = DataFrameManager() def __int__(self): return self.date
app.mixin.py class ShiftWithScheduleMixin(WeekCalendarMixin): def get_week_schedules(self, start, end, days): lookup = { '{}__range'.format(self.date_field): (start, end), } queryset = self.model.objects.filter(**lookup) days = {day: [] for day in days} df = pd.DataFrame(days) a=1 for schedule in queryset: if a == 1: user=schedule.user.last_name+' '+schedule.user.first_name date= schedule.date start_time=schedule.get_start_time_display() end_time = schedule.get_end_time_display() time = start_time+'-'+end_time ddf =pd.DataFrame({date:time},index =[user]) df = pd.concat([df,ddf],axis=0) df.fillna(" ", inplace=True) a = 2 if user != schedule.user.last_name+' '+schedule.user.first_name: user=schedule.user.last_name+' '+schedule.user.first_name date= schedule.date start_time=schedule.get_start_time_display() end_time = schedule.get_end_time_display() time = start_time+'-'+end_time ddf =pd.DataFrame({date:time},index =[user]) df = pd.concat([df,ddf],axis=0) df.fillna(" ", inplace=True) else: user=schedule.user.last_name+' '+schedule.user.first_name date= schedule.date start_time=schedule.get_start_time_display() end_time = schedule.get_end_time_display() time = start_time+'-'+end_time ddf =pd.DataFrame({date:time},index =[user]) df[date]= df[date].astype(str) df.at[user,date] =time df.fillna(" ", inplace=True) df.fillna(" ", inplace=True) print(df) print(pd.isnull(df)) return df def get_week_calendar(self): calendar_context = super().get_week_calendar() calendar_context['df'] = self.get_week_schedules( calendar_context['week_first'], calendar_context['week_last'], calendar_context['week_days'] ) return calendar_context
app.views.py #全ユーザー表示 class ShiftList(mixins.ShiftWithScheduleMixin, generic.ListView): model = Schedule template_name = 'app/shift_list.html' date_field = 'date' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) calendar_context = self.get_week_calendar() context.update(calendar_context) return context #店舗ごと作成途中 class ShopShiftList(mixins.ShopShiftWithScheduleMixin, generic.TemplateView): """ユーザーの一覧""" model = Schedule template_name = 'app/shopshift_list.html' date_field = 'date' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) shop = Shop_name.objects.all() context['shop'] = get_object_or_404(User, pk=self.kwargs['user_pk']) calendar_context = self.get_week_calendar() context.update(calendar_context) # context['df']=self.get_week_calendar() return context
urls.py app_name = 'app' urlpatterns = [ path('shift_list/', views.ShiftList.as_view(), name='shift_list'), path('shift_list/<int:year>/<int:month>/<int:day>/', views.ShiftList.as_view(), name='shift_list'), path('shop/<int:shop_pk>/shopshift_list/', views.ShopShiftList.as_view(), name='shopshift_list'), path('shop/<int:shop_pk>/shopshift_list/<int:year>/<int:month>/<int:day>/', views.ShopShiftList.as_view(), name='shopshift_list'), ]
現状上記のようになっています。
int:pkで指定すればしてフィルターにかければ良いのでは?と思っているのですが、上手く行きません。
初心者故codeがかなり煩雑になっていると思います、見づらくてすいません。
必要だと思われる部分のみ記載しました、他に必要であれば編集します。
アドバイスお願いします。
回答2件
あなたの回答
tips
プレビュー