Note that there are some explanatory texts on larger screens.

plurals
  1. PODjango ManyToMany 'str' object has no attribute
    primarykey
    data
    text
    <p>I am having an issue with what appears Django using the string name and not getting the "object" associated with that name. I'm trying to use a ManyToMany relationship, but I can't quite figure it out. The error I am getting is:</p> <pre><code>AttributeError at &lt;URL&gt; 'str' object has no attribute '_default_manager' </code></pre> <p>Here's my model setup:</p> <p><strong>models/hood.py</strong></p> <pre><code>class Hood(models.Model): name = models.CharField(unique=True) restaurants=models.ManyToManyField(Restaurant, through="restaurant_hood_map.RestaurantHoodMap") class Meta: db_table = "hoods" app_label="delivery" </code></pre> <p><strong>models/restaurant.py</strong></p> <pre><code>class Restaurant(models.model): name=models.ForeignKey(CompanyName) is_active=models.BooleanField(default=True) class Meta: db_table="restaurants" app_label="delivery" </code></pre> <p><strong>models/restuarant_hood_map.py</strong></p> <pre><code>&lt;import restaurant and hood&gt; class RestaurantHoodMap(models.Model): restaurant = models.ForeignKey(Restaurant) hood = models.ForeignKey(Hood) class Meta: db_table="restaurant_hood_map" app_label="delivery" </code></pre> <p>Now, I know what the problem is.....when I attempt to get the related restaurants off of Hood, I am getting this error. That's because it's treating the "restaurant.Restaurant" as a string value. However, I thought it was accepted to use string values in order to avoid circular dependencies? At least thats what I thought from the docs:</p> <p><a href="https://docs.djangoproject.com/en/dev/ref/models/fields/#foreignkey" rel="nofollow noreferrer">https://docs.djangoproject.com/en/dev/ref/models/fields/#foreignkey</a></p> <p>I also followed this example, which looked like exactly what I wanted:</p> <p><a href="https://stackoverflow.com/questions/4907913/how-do-i-tell-django-to-not-create-a-table-for-an-m2m-related-field">How do I tell Django to not create a table for an M2M related field?</a></p> <p>However, that doesn't seem to work when you get a Hood object and do hood.restaurants....it barfs.</p> <p>Any help would be AWESOME!</p> <p><strong>UPDATE:</strong> I made a slight change to the models to more accurately show what's happening.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload