1
我的模式是這樣的:從兩個Django模型獲取數據
class UserDevice(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=False)
device = models.ForeignKey(Device, on_delete=models.PROTECT, null=False)
activation_date = models.DateTimeField(default=timezone.now, null=False)
friendly_name = models.CharField(max_length=20, null=True, blank=True)
is_owner = models.BooleanField(null=False, default=False)
is_admin = models.BooleanField(null=False, default=True)
is_alerts_enabled = models.BooleanField(null=False, default=True)
timeStamp = models.DateTimeField(auto_now = True, null=False)
class UserProfile(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=False)
token = models.TextField(null=False, blank=True)
first_name = models.TextField(null=True, blank=True)
last_name = models.TextField(null=True, blank=True)
timeStamp = models.DateTimeField(auto_now = True, null=False)
我需要從userProfile
從UserDevice
和first_name, last_name, token
得到device, user, is_alerts_enabled, is_admin, is_owner
。這是我迄今爲止,它給了我我需要從userdevice
,但我不知道如何添加userprofile
東西。
nonOwners = UserDevice.objects.filter(device=device, is_owner=False)
if nonOwners is None:
return errormsg('non nonOwners found for this device')
nonOwnersArray=[]
for nonOwner in nonOwners:
nonOwner_data = model_to_dict(nonOwner,
fieldlist=(
'device.serial',
'user.email',
'is_alerts_enabled',
'is_admin',
'is_owner',
),
rename={
'device.serial': 'serial',
'user.email': 'email'})
nonOwnersArray.append(nonOwner_data)
任何幫助將不勝感激。謝謝!
[將Django模型對象轉換爲所有字段不變的可能的重複](https://stackoverflow.com/questions/21925671/convert-django-model-object-to-dict-with-all-of -the-fields-intact) – solarissmoke
不,這不是重複的。 –
這些模型之間的唯一聯繫是第三個模型:'用戶'。你確定你不想在'UserDevice'和'UserProfile'之間添加一個ForeignKey嗎? – raratiru