Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8444173
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 10, 20262026-06-10T09:20:16+00:00 2026-06-10T09:20:16+00:00

I have trouble writing a django data model which can link multiple objects of

  • 0

I have trouble writing a django data model which can link multiple objects of the same type back to a single data entry. Here’s are my current models:

class House(models.Model):
    name = models.CharField(max_length=200, unique=True)
    color = models.CharField(max_length=200, unique=True) 

class Config(models.Model)
   name = models.CharField(max_length=200)
   nbr_houses = models.PositiveIntegerField()
   houses = models.ManyToManyField(House) # this does not work, since I can only map a house once back to Config. 

I wanna do the following (pseudo-code):

# define a new config and enforce that is should have houses.
$ a = Config(name = 'new_config', nbr_houses = 3)
# associate individual houses with this config
$ a.houses[0] = House(pk= 1)
# associate the same house a second time with this config
$ a.houses[1] = House(pk= 1)
# associate a third house to config.
$ a.houses[2] = House(pk= 2)

I create a new Config object new_config and say that this configuration should have 3 houses. My model should then automatically check and force me to link the correct number of houses back to Config. Additionally, a House might reference back twice to the same configuration.

I was thinking of writing Config the following way

class Config(models.Model)
   name = models.CharField(max_length=200)
   nbr_houses = models.PositiveIntegerField()
   houses = models.ManyToManyField(House, related_name='house0')
   houses1 = models.ManyToManyField(House, related_name='house1')
   houses2 = models.ManyToManyField(House, related_name='house2')
   houses3 = models.ManyToManyField(House, related_name='house3')

to basically reflect the maximum number of associations possible, but that’s kinda inflexible. What’s a better way of accomplishing this?

EDIT: Imagine the following use case:
You want to write a computer game where you can define a complexity of a scene. Each scene is saved into a Config. Per scene, I can place x many houses. Houses don’t differ, they are just templates. So a scene could be made of 10 red houses, 2 blue houses and 1 yellow house. So for each Config entry I want to able to associate a different amount of houses (objects). Maybe later there will also be horses 🙂 I hope you get the idea.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-10T09:20:18+00:00Added an answer on June 10, 2026 at 9:20 am

    The question was updated to explain that you potentially want to associate some number of each house with the config. In order to do this in Django you need a new model, that Django calls a intermediate model. Like this:

    class ConfigHouses(model.Model):
        config = model.ForeignKey('Config')
        house = model.ForeignKey('House')
        count = model.PositiveIntegerField()
        class Meta:
            unique_together = ('config', 'house')
    

    and then in the Config class you declare a ManyToManyField and assign the intermediate model to the through parameter:

    class Config(model.Model):
        # ...
        houses = model.ManyToManyField('House', through = 'ConfigHouses')
    

    To add houses to a config you create new instances of the intermediate model:

    # Level 1 contains 4 red houses and 5 yellow houses
    c = Config.objects.get_or_create(name = 'level-1')
    
    red = House.objects.get_or_create(name = 'red')
    ch = ConfigHouses(config = c, house = red, count = 4)
    ch.save()
    
    yellow = House.objects.get_or_create(name = 'yellow')
    ch = ConfigHouses(config = c, house = yellow, count = 5)
    ch.save()
    

    After executing the above queries, the database will look something like this:

    CONFIG TABLE
    ----------------
    | pk | name    |
    |----|---------|
    |  1 | level-1 |
    ----------------
    
    HOUSE TABLE
    ----------------
    | pk | name    |
    |----|---------|
    |  1 | red     |
    |  2 | yellow  |
    ----------------
    
    CONFIGHOUSES TABLE
    -------------------------------
    | pk | config | house | count |
    |----|--------|-------|-------|
    |  1 |      1 |     1 |     4 |
    |  2 |      1 |     2 |     5 |
    -------------------------------
    

    To find out how many houses of a particular type there are in a particular config, you query the intermediate table, either directly, or via either one of the models:

    >>> ConfigHouses.objects.get(config = c, house__name = 'red').count
    4
    >>> c.confighouses.get(house__name = 'red').count
    4
    >>> yellow.confighouses_set.get(config = c).count
    5
    

    Original answer

    (The original question did not make it clear that the many-to-many relation needed multiplicity, but I’m leaving the original answer in place in case it’s useful.)

    Your original idea (that houses should be a ManyToManyField) is the right idea. It’s just that in order to refer to the House class before you define it, you need to pass the name of the class. See the Django documentation:

    If you need to create a relationship on a model that has not yet been defined, you can use the name of the model, rather than the model object itself.

    It’s also bad idea to have a nbr_houses field because it could become incorrect if someone updates the many-to-many relation without also remembering to update the nbr_houses field. You can use houses.count() to get the number of related houses.

    So your Config class should look like this:

    class Config(models.Model)
       name = models.CharField(max_length=200)
       # The class House is not yet defined, so refer to it by name.
       houses = models.ManyToManyField('House')
    

    And you can update the many-to-many relation using the RelatedManager interface: there are methods add, create, remove, clear, or you can just assign to it:

    config.houses = House.objects.filter(color = 'red')
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have trouble writing a recursive function in C: void func(int n) which for
I am having trouble writing a query. I have been working with UNION on
Im having some trouble writing a getstring function, this is what I have so
I'm quite new to sql and I'm having trouble writing this i have a
I have trouble doing this... You may want to get the same result as
I have some trouble writing some code (I might be tired), so I need
I have a Django application where users have additional data. That data is collected
I have a framework which works this way: After defining some meta data, it
I'm developing an app which will have a central database users can add entries
i have some trouble writing a method in Objective-C to make an object nil.

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.