我試圖在Django中創建一個具有自定義id屬性的模型。我希望它總是等於10000和該實例的當前ID號碼的總和。我到底該怎麼寫?我是否必須在視圖中做任何事情?在Django模型中創建一個自定義id字段
編輯:我最好把我使用的代碼,以防萬一。
models.py
class Schedules(models.Model):
course_name = models.CharField(max_length=128, choices=COURSE_NAME_CHOICES, default='a-plus')
location = models.CharField(max_length=128, choices=LOCATION_CHOICES, default='south_plainfield')
room = models.CharField(max_length=128, choices=ROOM_CHOICES, default='A')
start_date = models.DateField(auto_now=False, auto_now_add=False, default=datetime.date.today)
start_time = models.CharField(max_length=128, choices=START_TIME_CHOICES, default='eight-thirty am')
end_time = models.CharField(max_length=128, choices=END_TIME_CHOICES, default='eight-thirty am')
instructor = models.CharField(max_length=128, choices=INSTRUCTOR_CHOICES, default='adewale')
total_hours = models.CharField(max_length=128, choices=TOTAL_HOURS_CHOICES, default='six')
hours_per_class = models.CharField(max_length=128, choices=HOURS_PER_CLASS_CHOICES, default='four_and_half')
frequency = models.CharField(max_length=128)
status = models.CharField(max_length=128, choices=STATUS_CHOICES)
interval = models.CharField(max_length=128, choices=INTERVAL_CHOICES, default='1 day')
initiated_by = models.CharField(max_length=128, null=True)
schedule_id = models.IntegerField(default=0)
views.py
def start_One_Schedule(request):
form = ScheduleForm()
if request.method == 'POST':
form = ScheduleForm(request.POST)
if form.is_valid():
obj = form.save(commit=False)
obj.initiated_by = request.user.username
obj.save()
return render(request, 'schedule/schedule.html', {})
else:
print(form.errors)
return render(request, 'schedule/start_one_schedule.html', {'form': form})
我添加了我的代碼。我需要做到這一點,以免它干擾我的其他領域。 –
我已添加註釋以詳細說明我的代碼。它不會干擾你的其他領域。 –
難道你不應該把'* args,** kwargs'傳遞給super嗎? – schillingt