EzzatA
EzzatA

Reputation: 114

Django model relates to two other models

I'm trying to build a dictionary application and having a difficulty with the model.

Now I wrote this

class Term(models.Model):
    term_text   = models.CharField("phrase term text", max_length=100)

class Definition(models.Model): 
    term                    = models.ForeignKey(Term)
    definition_text         = models.TextField()


class Country(models.Model):
        #is this correct method?
        #Should i add ForeginKey for both Term and Definition here?

The problem is the Country. Both Term and Definition should have a Country field as Term could be available in many countries and a definition could be limited to certain countries with another definition for others.

now how to do this country model?

I've tried to use django-countries as a model field for Term and Definition but its limiting me to use only 1 country per object.

Upvotes: 1

Views: 73

Answers (1)

Dayne Jones
Dayne Jones

Reputation: 153

What you want is ManyToMany relationships on both Term and Definition. That way you'll be able to call my_term.countries and my_definition.countries.

class Term(models.Model):
    term_text = models.CharField("phrase term text", max_length=100)
    country = models.ManyToManyField(Country)


class Definition(models.Model): 
    term = models.ForeignKey(Term)
    definition_text = models.TextField()
    country = models.ManyToManyField(Country)


class Country(models.Model):
    # define Country model

    class Meta:
        verbose_name_plural = "countries"

Upvotes: 1

Related Questions