I am new to Django and Python. Let's say I am building an app to manage devices used by users in companies. I have multiple companies, with multiple users and rooms in each.
Rooms and users are always linked to a company.
A device can be linked to:
- An user ("Joe's iPhone", "Anna's Laptop")
- A room ("Conference Room's Computer")
A device is always linked to a company.
So, I can have a device, that is linked to a company only.
So here's my code :
models.py:
class Company(models.Model):
name=models.CharField(max_length=50)
class User(models.Model):
name=models.CharField(max_length=50)
company=models.ForeignKey('Company', on_delete=models.CASCADE)
class Room(models.Model):
name=models.CharField(max_length=50)
company=models.ForeignKey('Company', on_delete=models.CASCADE)
class Device(models.Model):
company=models.ForeignKey('Company', on_delete=models.CASCADE)
user=models.ForeignKey('User', on_delete=models.CASCADE, blank=True, null=True)
room=models.ForeignKey('Room', on_delete=models.CASCADE, blank=True, null=True)
admin.py:
class DevicesInline(admin.TabularInline):
model = Device
extra = 0
def formfield_for_foreignkey(self, db_field, request=None, **kwargs):
if db_field == "Company":
kwargs['queryset'] = ## Here I don't know ##
return super().formfield_for_foreignkey(db_field, request, **kwargs)
class UserAdmin(admin.ModelAdmin):
inlines = [DeviceInline]
What I want is pretty simple : when I am editing a user (or a room), I want to be able to add a device for it. But the field Company
has to be filled with the company for the user or room, and it can't be modified. That's all :)
PS: I don't know if the device needs to be linked to the company if it's already linked to a user or room ? That's a whole other question.