Search code examples
pythondjangodjango-taggit

Adding multiple tags to model


I have the following model:

class Investor(Profile):
ROLE = (
    ('AN', 'Angel Investor'),
    ('VC', 'Venture Capital'),
    ('SC', 'Seed Capital')
)
role = models.CharField(max_length=2, default='AN', choices=ROLE)
min_inv = models.DecimalField(
    default=0, max_digits=20, decimal_places=2,
    verbose_name='Minimum Investments per year')
max_inv = models.DecimalField(
    default=0, max_digits=20, decimal_places=2,
    verbose_name='Maximum investments per year')
no_startups = models.IntegerField(
    default=0, verbose_name='Number of investments per year')
rating_sum = models.FloatField(default=0)
no_raters = models.IntegerField(default=0)

I want to add multiple tags to this model. - Category - Stage - Funding

I want investors to be assigned to multiple categories, stages, and funding. So an investor can be tied to multiple Categories and multiple Stages and multiple Funding types.

How can I edit the model to do so?


Solution

  • can you just add ManyToMany relationships for the connected models??

    class Investor(Profile):
      ROLE = (
        ('AN', 'Angel Investor'),
        ('VC', 'Venture Capital'),
        ('SC', 'Seed Capital')
      )
      role = models.CharField(max_length=2, default='AN', choices=ROLE)
      min_inv = models.DecimalField(
        default=0, max_digits=20, decimal_places=2,
        verbose_name='Minimum Investments per year')
      max_inv = models.DecimalField(
        default=0, max_digits=20, decimal_places=2,
        verbose_name='Maximum investments per year')
      no_startups = models.IntegerField(
        default=0, verbose_name='Number of investments per year')
      rating_sum = models.FloatField(default=0)
      no_raters = models.IntegerField(default=0)
      categories = models.ManyToMany(Category)
      stages = models.ManyToMany(Stage)
      fundings = models.ManyToMany(Funding)
    

    Using manytomany you can then assign stages

    investor = Investor.objects.all()[0]
    investor.categories.add(category_instance_one, category_instance_two)
    investor.categories.all() # retrieves all categories that this investor has