Beginner: ManyToManyFields error creating the model / adding values by the Admin Module or the Shell

87 views
Skip to first unread message

lnzy...@gmx.de

unread,
Nov 4, 2014, 7:12:56 AM11/4/14
to django...@googlegroups.com
Hi,
Unfortunately I have not found any Intel at the django documentation, in the Getting Started With Django book or the Two Scoops of Django book.  So I hope someone in the community will sacrifice his nerves and time, and gives me a hint / explanation of my misunderstanding.
 
I have the following classes / models in my models.py:
class Author(models.Model):
    author= models.CharField(max_length=255, verbose_name="Author name")
    def __str__(self):
        return self.author
 
class Language(models.Model):
    ENGLISH = 'en'
    GERMAN = 'de'
    FRENCH = 'fr'
    NOT_AVAILABLE = ''
    LANGUAGE_CHOICES = (
        (ENGLISH, 'English'),
        (GERMAN, 'German'),
        (FRENCH, 'French'),
        (NOT_AVAILABLE, ''),
    )
    language = models.CharField(max_length=32,choices=LANGUAGE_CHOICES,default=NOT_AVAILABLE)
    def __str__(self):
        return self.language
 
 
class User(models.Model):
    user_name = models.CharField(max_length=128, verbose_name="Username")
    user_email = models.EmailField(verbose_name="User E-Mail address")
    interests = models.ManyToManyField(Interest, verbose_name="User interessts")
    def __str__(self):
        return ' '.join([
        self.user_name,
        self.user_email])
   
class Interest(models.Model):
    author = models.ManyToManyField(Author, verbose_name="Author name")
    language = models.ManyToManyField(Language, verbose_name="Book language", blank=True)
    def __str__(self):
        return ' '.join([
            self.author,
            self.language])
 
Now I try to add some User with an Interest using the Admin module or the Shell to find out how to do that (real syntax and model) by the “site”. But unfortunately both the shell and furthermore the graphical admin module give me an error, whenever I try to add the data to an user.
Where is my error? What do I miss? My idea is, that every User has (many) Interests and an Interest is defined by an Author who he likes as well as a “possible” language in which he writes.
 
So hopefully someone seas my probably basic-error very fast!
Thank you very much!
Mike

Erik Cederstrand

unread,
Nov 4, 2014, 9:00:55 AM11/4/14
to Django Users
> Den 04/11/2014 kl. 10.57 skrev lnzy...@gmx.de:
> [...]
> Now I try to add some User with an Interest using the Admin module or the Shell to find out how to do that (real syntax and model) by the “site”. But unfortunately both the shell and furthermore the graphical admin module give me an error, whenever I try to add the data to an user.
> Where is my error? What do I miss?

Yes, where IS your error? You forgot to attach the error message.

Erik

lnzy...@gmx.de

unread,
Nov 4, 2014, 1:16:57 PM11/4/14
to django...@googlegroups.com
Hi,
Sorry, via the admin interface (Web-GUI) I have inserted the following values:
My Actions
en
Language

mike.test // te...@test.de
User
 
Dan Brown
Author
 
If I now try to add an Interest (“Dan Brown” and “en”) via the GUI selection I get:
TypeError at /admin/BookReminder/interest/add/
sequence item 0: expected string, ManyRelatedManager found
Request Method:
POST
Request URL:
Django Version:
1.7
Exception Type:
TypeError
Exception Value:
sequence item 0: expected string, ManyRelatedManager found
Exception Location:
D:\D-Project\SOL\BookReminder\models.py in __str__, line 39
Python Executable:
C:\Python27\python.exe
Python Version:
2.7.6
Python Path:
['D:\\D-Project\\SOL',
 'C:\\Windows\\system32\\python27.zip',
 'C:\\Python27\\DLLs',
 'C:\\Python27\\lib',
 'C:\\Python27\\lib\\plat-win',
 'C:\\Python27\\lib\\lib-tk',
 'C:\\Python27',
 'C:\\Python27\\lib\\site-packages']
Server time:
Tue, 4 Nov 2014 18:48:34 +0100
 
So for me it looks like in the Model there is an error? Otherwise it should work via the GUI that gives me the two fields as input possibilites. The same happens, if I try to add the interesst by using the user in the admin interface and click there on "add" interest.
 
Best Regards,
Mike

Erik Cederstrand

unread,
Nov 4, 2014, 4:42:45 PM11/4/14
to Django Users
> Den 04/11/2014 kl. 19.16 skrev lnzy...@gmx.de:
>
> Hi,
> Sorry, via the admin interface (Web-GUI) I have inserted the following values:
> My Actions
> en
> Language
>
> mike.test // te...@test.de
> User
>
> Dan Brown
> Author
>
> If I now try to add an Interest (“Dan Brown” and “en”) via the GUI selection I get:
> TypeError at /admin/BookReminder/interest/add/
> sequence item 0: expected string,ManyRelatedManager found

It looks like the Interest model is supposed to connect one author with one language. In that case, the fields the Interest class should be models.ForeignKey, not models.ManyToManyField.

Erik

lnzy...@gmx.de

unread,
Nov 4, 2014, 5:09:49 PM11/4/14
to django...@googlegroups.com
 
Hi Erik,
 
the idea was, that one Author can write in more than one language (eg. en and de), or no one at all. This was the background to use the ManyToManyField. 
But the "error" Message must have an other reason?
 
Best Regards,
Mike
Gesendet: Dienstag, 04. November 2014 um 22:42 Uhr
Von: "Erik Cederstrand" <erik+...@cederstrand.dk>
An: "Django Users" <django...@googlegroups.com>
Betreff: Re: Beginner: ManyToManyFields error creating the model / adding values by the Admin Module or the Shell
--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/4736339F-EEBA-41C6-B9E7-D12B161A0B46%40cederstrand.dk.
For more options, visit https://groups.google.com/d/optout.
 
 

Erik Cederstrand

unread,
Nov 5, 2014, 5:07:17 AM11/5/14
to Django Users
> Den 04/11/2014 kl. 23.07 skrev lnzy...@gmx.de:
>
>
> Hi Erik,
>
> the idea was, that one Author can write in more than one language (eg. en and de), or no one at all. This was the background to use the ManyToManyField.

Yes, but then you simply create multiple Interest objects, right? One for every author-language combination. Your field names are singular, not plural, which tells me you should use a ForeignKey field. The current Interest model links multiple Authors with multiple Languages, which doesn't make much sense.

If you want to use ManyToManyField, then you put a "interests" field to Language directly on the Author model.

> But the "error" Message must have an other reason?

The direct cause is that you are trying to print self.author in the __str__ method. self.author is a ManyRelatedManager, so you should use self.authors.all() to access the individual authors. But you should change you models instead of fixing this error :-)

Erik

lnzy...@gmx.de

unread,
Nov 6, 2014, 2:52:17 PM11/6/14
to django...@googlegroups.com
 
Hey Erik,
 
you are total right. the __str__ method was chausing the error!
Thank you so much! Now I can try to make progress!
 
I very much appreached your help!
Best Regards,
Mike
 
Gesendet: Mittwoch, 05. November 2014 um 11:06 Uhr

Von: "Erik Cederstrand" <erik+...@cederstrand.dk>
An: "Django Users" <django...@googlegroups.com>
Betreff: Re: Beginner: ManyToManyFields error creating the model / adding values by the Admin Module or the Shell
--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.

lnzy...@gmx.de

unread,
Nov 26, 2014, 1:55:25 PM11/26/14
to django...@googlegroups.com
Hi,
let’s assume I have the following model:
 
class Ingredient(models.Model):
    ingredient= models.CharField(max_length=255)
class Dish(models.Model):
    BREAKFAST = 'bf'
    LUNCH = 'l'
    DINNER = 'D'
    DISH_CHOICES = (
        (BREAKFAST, 'Breakfast'),
        (LUNCH, 'Lunch'),
        (DINNER, 'Dinner'),
    )
    dish = models.CharField(max_length=32,choices=DISH_CHOICES,unique=True)
 
class Preference(models.Model):
    ingredient= models.ForeignKey(Ingredient)
    dish = models.ForeignKey(Dish)
    date_created = models.DateTimeField(auto_now_add=True)
    date_updated = models.DateTimeField(auto_now=True, verbose_name='Date updated')
    owner  = models.ForeignKey(User, related_name='preferences')
 
class Meal(models.Model):
    name = models.CharField(max_length=255)
    ingredient= models.ManyToManyField(Ingredient)
    kalorins = models.IntegerField()
    thumbnail = models.URLField(blank=True)
    dish= models.ForeignKey(Dish)

I want to execute a database query in the view resulting all meals that would match the preference’s of a user.
But something like: result = Meal.objects.filter(ingredient__in=user.request.name.pfreferences) will select all the meals witch are in the preference list of the user, regardless his choice of the “Dish Type”. So if a person only likes tomatos for breakfast, he also will get all meals with tomates for lunch and dinner.
 
So I am looking for a way, which returns only the “Meals” where the ingredients and the dish BOTH match the ingredients and the dish of the user’s Preference.
I haven’t found anything in the django books I have or the documentation
Thanks a lot.
Best Regards,
Mike
 
 

Vijay Khemlani

unread,
Nov 26, 2014, 2:30:36 PM11/26/14
to django...@googlegroups.com
I think you could construct a Q object like this:

from django.db.models import Q

query = Q()
for preference in user.preferences.all():
    query |= Q(dish=preference.dish) & Q(ingredient=preference.ingredient)

Meal.objects.filter(query)

That returns the meals where their (ingredient, dish) combination match at least one of the preferences of the user.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.

lnzy...@gmx.de

unread,
Nov 27, 2014, 2:58:11 AM11/27/14
to django...@googlegroups.com
Hi Vijay,
 
thank you very much. I have not known, that |= also could be used on Q().
Thought Q is only there for making "or" "not" and so stuff of calls! Great!
 
Best Regards,
Mike
 
Gesendet: Mittwoch, 26. November 2014 um 20:30 Uhr
Von: "Vijay Khemlani" <vkhe...@gmail.com>
An: django...@googlegroups.com
Betreff: Re: How to make database queries that “filters” results according to tuples of values?

Vijay Khemlani

unread,
Nov 27, 2014, 9:10:31 AM11/27/14
to django...@googlegroups.com
Remember that |= is just a shorthand for

query = query | ... rest of parameters

So in the end it is just an "or" like you say, nothing magical about that

Glad I could help

Regards!

Reply all
Reply to author
Forward
0 new messages