Reputation: 317
I guess there is already been a lot of discussions available almost went through all of them but still facing this error.
class Device(models.Model):
"""Storing Device ids """
platform = models.CharField(max_length=3, choices=PLATFORM, default = 'ANR')
dev_id = models.CharField(max_length = 255, null=True, blank=False)
def __str__(self):
return str(self.id)
class UserProfile(models.Model):
user = models.OneToOneField('user.User',
on_delete=models.CASCADE,
related_name='profile',
primary_key=True,
unique=True)
device = models.ManyToManyField(Device, related_name='devices')
def __str__(self):
return str(self.user)
Error 1
username = UserProfile.objects.filter(
phone_number=user_username).get()
username.device.dev_id
*** AttributeError: 'ManyRelatedManager' object has no attribute 'dev_id'
Error 2 After Some Research
username.device.values_list('dev_id', flat=True)
<QuerySet []>
```
There is no device found with this user but there are devices in them for this username
For the reference, I have listed devices
```python
>>> Device.objects.all()
<QuerySet [<Device: 1>]>
Error 3
(Pdb) username.device.all()
<QuerySet []>
Checked with this Method but not able to list devices
Upvotes: 2
Views: 14176
Reputation: 2847
This cannot work, because device
is a ManyToMany
Relationship.
A user can obviously have multiple devices (or none) associated.
If you want to access all devices from a user, try the following:
user.device.all()
this will give you a QuerySet
from a RelatedManager
. Just use it like a regular QuerySet
:
for d in user.device.all():
print(d.dev_id)
This, of course, is described in the documentation.
Upvotes: 14