私はかなり新しいdjangoです。私は2つのクラスをデータベースで一緒に使うようにしています。ユーザプロファイルをdjangoの他のクラスとリンクする(postgresql db内)
models.py
class Device(models.Model):
deviceNb = models.CharField(max_length = 50, null=True)
temperature = models.IntegerField()
battery = models.IntegerField()
class UserProfile(models.Model):
user = models.OneToOneField(User)
profession= models.CharField(max_length=50, null=True)
device = models.OneToOneField(Device, null=True) # null = true is to allow null values for devices
User.profile = property(lambda u : UserProfile.objects.get_or_create(user=u)[0])
forms.py
(Iは、PostgreSQLデータベースを使用しています)より正確には、私は、ユーザーがデバイスを作成することができるようにしたいし、データベース内のユーザーとデバイスをリンクclass DeviceForm(forms.ModelForm):
class Meta:
model = Device
fields = ('deviceNb', 'temperature', 'battery',)
class UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ('profession',)
views.py
def user_profile(request):
user = request.user
profile = user.profile
device = profile.device
if request.method == 'POST':
#we want to populate the form with the original instance of the profile model and insert POST info on top of it
device_form = DeviceForm(request.POST, instance=device)
if device_form.is_valid():
dev = device_form.save()
device = dev
form = UserProfileForm(request.POST, instance=profile)
if form.is_valid():
form.save()
#to go back to check that the info has changed
return HttpResponseRedirect('/accounts/loggedin')
else:
form = UserProfileForm(instance=profile)
device_form = DeviceForm(instance=device)
args = {}
args['form'] = form
args['device_form'] = device_form
return render(request, 'profile.html', args)
さて、PostgreSQLで、私は次のテーブルを持っている:
userprofile_userprofile(次の表の列が含まれています):
id : OK (filled)
user_id : OK (filled)
device_id : PROBLEM : NOT FILLED
profession : OK (filled)
userprofile_device(次の表の列が含まれています):
id : OK
temperature: OK
battery: OK
deviceNb : OK
事は、私が持ってできるようにしたいですユーザとデバイスが両方ともリンクされるように、ユーザが既に作成したものに関連付けられたデバイスID
。上の** models.py **関係に基づいて、あなたはpythonで 'user_profile.device.id'を実行することによってデバイスIDにアクセスする必要があります。 –