'Assign clients to seller
In my application there are two types of users, sellers and clients. Each client must be assigned to exactly one seller but a seller can have multiple clients.
I have created one usermodel, so all my users are saved in the same place. In the model there is a boolean field called "is_seller" and another boolean field called "is_client". These get set to true depending on which registration form the user use.
The client must be assigned when they register but I am not able to get my head around how I should implement this logic. I would appreciate all sorts of guidance!
Solution 1:[1]
If I were you I'd do something like:
class Person(models.Model):
class Meta:
abstract = True
user = models.OneToOne(User, on_delete=models.CASCADE)
def is_seller(self):
return hasattr(self, 'seller')
def is_client(self):
return hasattr(self, 'client')
class Seller(Person):
pass
class Client(Person):
seller = models.ForeignKey(Seller,
on_delete=models.CASCADE,
related_name="clients")
So from this you can do this:
# example to read a person:
p = Person.objects.get(pk=1)
# if he's a seller, display all his clients:
if p.is_seller():
for client in p.clients.all():
print(f"Seller {p} has this client: {client}")
And the opposite: if he's a client, display his seller
# example to read a person:
p = Person.objects.get(pk=1)
# if he's a client, display all his seller:
if p.is_client():
print(f"Client {p} has this seller: {p.seller}")
I didn't test it but it's very close to a well-tested code.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Olivier Pons |
