简体   繁体   中英

Django ManyToMany Through Relationship

I have a following criteria

where I have User Model, which itself extended was from Django user model.

Class User
   name = models.CharField()
   ...

A user can become a seller when he is approved by the admin. Seller model goes like this.

Class Seller
    location = models.CharField()
    INDIVIDUAL = '1'
    COMPANY = '2'
    ACCOUNT_CHOICES = (
        (INDIVIDUAL, 'individual'), 
        (COMPANY, 'company'),
    )

    account_type_name = models.CharField(max_length=2,choices=ACCOUNT_CHOICES, default=INDIVIDUAL)

And Seller can belong to any of the second or third level categories

Class Level1Category
    name = models.CharField()

Class Level2Category
    name = models.CharField()
    level1 = models.ForeignKey(Level1Category)

Class Level3Category
    name = models.CharField()
    level2 = models.ForeignKey(Level2Category)

When a user apply for seller account he has to select any one of the level 2 or level 3 category. Which would be the efficient model architecture for this. How can I link the category model with the seller and also link these two models with the user.

EDIT

My User Model is already a extended version of Django User Model. I'm doing that because I have two different type of profiles, one is seller and the other is buyer.

I would suggest you try by extending Django's User model ( see docs )

Your seller would extend from your User model:

class User(models.Model):
    name = models.CharField()
    ....

class Seller(models.Model):
   user = models.OneToOneField(User, on_delete=models.CASCADE)
   location = models.CharField()
   ...

You could create a ManyToMany relationship for your categories ( see docs ):

class Category(models.Model):
    name = models.CharField()
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    ...

Or one thing that come to mind, you maybe could extend what you have done for your account_type_name:

LEVEL_CATEGORY = (
    (1, 'Level 1'), 
    (2, 'Level 2'),
    (3, 'Level 2'),
)

level_category = models.CharField(choices=LEVEL_CATEGORY, default=1)

But I am not sure if this is really what you want to do.

If you need just basic user field such as; name, email etc, you can extend Django's User model as @HendrikF suggest then;

class Seller(models.Model):
   user = models.OneToOneField(User, on_delete=models.CASCADE)
   location = models.CharField()
   ...

if you need customize User model I do suggest you Django AbstractUser for example;

from django.contrib.auth.models import AbstractUser

class User(AbstractUser):
    consumer = models.ForeignKey('Consumer', null=True, blank=True)
    ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM