Following regular manytomany queryset logic gives me errors. I guess since its related to self, I might need to do some extra magic, but i can't figure out what magic.
model:
class Entry(models.Model):
title = models.CharField(max_length=100, verbose_name='title')
related = models.ManyToManyField('self', related_name='related_entries', blank=True)
queryset:
entry = Entry.objects.get(pk=1)
related = entry.related_entries.all()
error: 'Entry' object has no attribute 'related_entries'
Look at the documentation for the symmetrical argument to ManyToManyField:
When Django processes this model, it identifies that it has a ManyToManyField on itself, and as a result, it doesn't add a person_set attribute to the Person class. Instead, the ManyToManyField is assumed to be symmetrical -- that is, if I am your friend, then you are my friend.
If you do not want symmetry in many-to-many relationships with self, set symmetrical to False. This will force Django to add the descriptor for the reverse relationship, allowing ManyToManyField relationships to be non-symmetrical.
So, in order to use the related_name, set symmetrical=False.
Related
I looked in the QuestSet API and tried to find the answer. But i guess i am misinterpreting the distinction between a Manager and an instance.
I have the following model...
class Target(model.Model):
group = models.ManyToManyField(Group, null=True)
group_name = models.ManyToManyField(GroupName, null=True)
...
class Group(models.Model):
value = models.CharField(null=True)
And so on is defined for all the ManyToMany relations in the Target Model.
Now, i have a reference to the Target Model itself from another model as follows.
class Schedule(models.Model):
targetID = models.ForeignKey(Target, null=True)
name = models.CharField(null=True)
In my template for the Schedule model, I want to be able to display the values of the ManyToManyFields which are referenced in the ForeignKey (i.e the Target).
When i write the following,
o = Schedule.objects.get(name = 'O_123')
o.targetID ---> This gives me the ID of the ForeignKey field
I want to be able to display the value of all the field which are there in the Target Model with reference to the name(i.e. O_123), For this i tried the following,
o.targetID.group
this displays "django.db.models.fields.related.ManyRelatedManager object at 0x1f2e850"
Can someone help me understand what am I misinterpreting. Thanks.
You have some misconceptions.
o.targetID ---> This gives me the ID of the ForeignKey field
No. o.targetID gives you the actual Target object that is related via your ForeignKey. That's why you should not call the field anythingID: it should just be called target.
Now, this is possible because that is the many-to-one side of the FK relationship: ie, for each Schedule, there is only one Target. But from Target to Group there is a many-to-many relationship. So o.targetID.group refers to many groups (again, naming conventions help: you should probably call this field groups).
So Django gives you a Manager object: basically, just the same as when you do Schedule.objects. Just as with that latter case, you can do all() to get all of the elements to iterate over, or get(criteria=value) to get a specific one, or even filter(criteria=value) to get a filtered queryset.
In your case, you probably want:
for group in o.targetID.group.all():
print group.my_field_value
This is my code:
class Resource(models.Model):
[...]
class Theme(models.Model):
[...]
resource_set = models.ManyToManyField(Resource, through='Match', related_name='theme_set', blank=True)
class Match(models.Model):
resource = models.ForeignKey(Resource)
theme = models.ForeignKey(Theme)
[...]
I am intentionally using an intermediate model, because I want to add some attributes to the relationship. Now... I know that when declaring many-to-many relationship in Theme, I am also getting a reverse relationship from Resource. See the related_name I'm using? This way I have "symmetrical" field names in both models (resource_set, theme_set, and match_set in both models).
My problem is that when I generate forms from both models (Resource and Theme) they are not symmetrical. When I generate a Theme form I automatically get a multiple choice field to choose from the already existing Resources. But when I generate a Resource form I don't.
So that is why I would like to declare many-to-many relationship in both models - to make them really equal (not like in the Pizzas and Toppings example ;) and to have these additional multiple choice fields generated.
The question is - is it possible, or do I have to add the multiple choice field to the ResourceForm myself or use FormSets which I don't understand yet?
BTW - as I can't save a new Theme from ThemeForm using save() ("Cannot set values on a ManyToManyField which specifies an intermediary model.") I do this:
[...]
theme = form.save(commit=False)
theme.save()
for resource in form.cleaned_data['resource_set']:
match = Match()
match.resource = resource
match.theme = theme
match.save()
return redirect([...]
You can simply define it on both sides.
One problem would be the related_name - As far as I know, there is no way of telling the ORM "I'll take care of the reverse relation myself". So you'll need to change the related_names so they don't clash with the real field names. In this example I added underscore to the related_names, so Resource objects now have both theme_set and _theme_set, which are two handles to the same data.
class Resource(models.Model):
[...]
theme_set = models.ManyToManyField('Theme',
through='Match',
related_name='_resource_set',
blank=True)
class Theme(models.Model):
[...]
resource_set = models.ManyToManyField(Resource,
through='Match',
related_name='_theme_set',
blank=True)
Also, if you're using South, you may need to add_ignored_fields to one of the field.
I wanted all instances in all tables to have an object instance. A one to one primary key field looked like a good way to do this. Like a small example below.
from util.fields import BigAutoField,BigForeignKey
from django.db import models
class Common_document(models.Model):
pk = models.OneToOneField("Type_object", primary_key=True, related_name="common_document_content_pk")
author = models.ManyToManyField("Type_object", related_name = 'common_document_author',
limit_choices_to = {"Common_document_author_author":"Type_object"} ,null = True,
through = 'Common_document_author', blank = True)
#....
class Common_document_author(models.Model):
pk = models.OneToOneField("Type_object", primary_key=True, related_name="common_document_author_pk")
document = BigForeignKey("Common_document", related_name='Common_document_author_document')
author = BigForeignKey("Type_object", related_name='Common_document_author_author')
class Type_object(models.Model):
id = BigAutoField(primary_key=True)
#....
# Some of the fields are m2m
However this gave the following error:
django.core.management.base.CommandError: One or more models did not validate:
schema.common_document: Intermediary model Common_document_author has more than
one foreign key to Type_object, which is ambiguous and is not permitted.
This error is removed if I comment out the pk field in the document_author table. I guess the error comes because django is not sure witch object FK to use. How do i fix this? Is there a way to tell django which field in the m2m table to be used in the m2m field?
I am probably not going to do it like this. m2m tables are probably not going to need to have an object instance, but I would still like to know how to do this.
I guess I don't understand you motivation. Why do you want to use a foreign key as your primary index? Sure, index it, but primary?. You might also try changing its name from 'pk', I am sure Django makes assumptions about the field called 'pk'.
This is how my models look:
class QuestionTagM2M(models.Model):
tag = models.ForeignKey('Tag')
question = models.ForeignKey('Question')
date_added = models.DateTimeField(auto_now_add=True)
class Tag(models.Model):
description = models.CharField(max_length=100, unique=True)
class Question(models.Model):
tags = models.ManyToManyField(Tag, through=QuestionTagM2M, related_name='questions')
All I really wanted to do was add a timestamp when a given manytomany relationship was created. It makes sense, but it also adds a bit of complexity. Apart from removing the .add() functionality [despite the fact that the only field I'm really adding is auto-created so it technically shouldn't interfere with this anymore]. But I can live with that, as I don't mind doing the extra QuestionTagM2M.objects.create(question=,tag=) instead if it means gaining the additional timestamp functionality.
My issue is I really would love to be able to preserve my filter_horizontal javascript widget in the admin. I know the docs say I can use an inline instead, but this is just too unwieldy because there are no additional fields that would actually be in the inline apart from the foreign key to the Tag anyway.
Also, in the larger scheme of my database schema, my Question objects are already displayed as an inline on my admin page, and since Django doesn't support nested inlines in the admin [yet], I have no way of selecting tags for a given question.
Is there any way to override formfield_for_manytomany(self, db_field, request=None, **kwargs) or something similar to allow for my usage of the nifty filter_horizontal widget and the auto creation of the date_added column to the database?
This seems like something that django should be able to do natively as long as you specify that all columns in the intermediate are automatically created (other than the foreign keys) perhaps with auto_created=True? or something of the like
There are ways to do this
As provided by #obsoleter in the comment below : set QuestionTagM2M._meta.auto_created = True and deal w/ syncdb matters.
Dynamically add date_added field to the M2M model of Question model in models.py
class Question(models.Model):
# use auto-created M2M model
tags = models.ManyToMany(Tag, related_name='questions')
# add date_added field to the M2M model
models.DateTimeField(auto_now_add=True).contribute_to_class(
Question.tags.through, 'date_added')
Then you could use it in admin as normal ManyToManyField.
In Python shell, use Question.tags.through to refer the M2M model.
Note, If you don't use South, then syncdb is enough; If you do, South does not like
this way and will not freeze date_added field, you need to manually write migration to add/remove the corresponding column.
Customize ModelAdmin:
Don't define fields inside customized ModelAdmin, only define filter_horizontal. This will bypass the field validation mentioned in Irfan's answer.
Customize formfield_for_dbfield() or formfield_for_manytomany() to make Django admin to use widgets.FilteredSelectMultiple for the tags field.
Customize save_related() method inside your ModelAdmin class, like
def save_related(self, request, form, *args, **kwargs):
tags = form.cleaned_data.pop('tags', ())
question = form.instance
for tag in tags:
QuestionTagM2M.objects.create(tag=tag, question=question)
super(QuestionAdmin, self).save_related(request, form, *args, **kwargs)
Also, you could patch __set__() of the ReverseManyRelatedObjectsDescriptor field descriptor of ManyToManyField for date_added to save M2M instance w/o raise exception.
From https://docs.djangoproject.com/en/dev/ref/contrib/admin/#working-with-many-to-many-intermediary-models
When you specify an intermediary model using the through argument to a ManyToManyField, the admin will not display a widget by default. This is because each instance of that intermediary model requires more information than could be displayed in a single widget, and the layout required for multiple widgets will vary depending on the intermediate model.
However, you can try including the tags field explicitly by using fields = ('tags',) in admin. This will cause this validation exception
'QuestionAdmin.fields' can't include the ManyToManyField field 'tags' because 'tags' manually specifies a 'through' model.
This validation is implemented in https://github.com/django/django/blob/master/django/contrib/admin/validation.py#L256
if isinstance(f, models.ManyToManyField) and not f.rel.through._meta.auto_created:
raise ImproperlyConfigured("'%s.%s' "
"can't include the ManyToManyField field '%s' because "
"'%s' manually specifies a 'through' model." % (
cls.__name__, label, field, field))
I don't think that you can bypass this validation unless you implement your own custom field to be used as ManyToManyField.
The docs may have changed since the previous answers were posted. I took a look at the django docs link that #Irfan mentioned and it seems to be a more straight forward then it used to be.
Add an inline class to your admin.py and set the model to your M2M model
class QuestionTagM2MInline(admin.TabularInline):
model = QuestionTagM2M
extra = 1
set inlines in your admin class to contain the Inline you just defined
class QuestionAdmin(admin.ModelAdmin):
#...other stuff here
inlines = (QuestionTagM2MInline,)
Don't forget to register this admin class
admin.site.register(Question, QuestionAdmin)
After doing the above when I click on a question I have the form to do all the normal edits on it and below that are a list of the elements in my m2m relationship where I can add entries or edit existing ones.
D:\zjm_code\basic_project>python manage.py syncdb
Error: One or more models did not validate:
topics.topic: Accessor for field 'content_type' clashes with related field 'Cont
entType.topic_set'. Add a related_name argument to the definition for 'content_t
ype'.
topics.topic: Accessor for field 'creator' clashes with related field 'User.crea
ted_topics'. Add a related_name argument to the definition for 'creator'.
topics.topic: Reverse query name for field 'creator' clashes with related field
'User.created_topics'. Add a related_name argument to the definition for 'creato
r'.
topicsMap.topic: Accessor for field 'content_type' clashes with related field 'C
ontentType.topic_set'. Add a related_name argument to the definition for 'conten
t_type'.
topicsMap.topic: Accessor for field 'creator' clashes with related field 'User.c
reated_topics'. Add a related_name argument to the definition for 'creator'.
topicsMap.topic: Reverse query name for field 'creator' clashes with related fie
ld 'User.created_topics'. Add a related_name argument to the definition for 'cre
ator'.
You have a number of foreign keys which django is unable to generate unique names for.
You can help out by adding "related_name" arguments to the foreignkey field definitions in your models.
Eg:
content_type = ForeignKey(Topic, related_name='topic_content_type')
See here for more.
http://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.related_name
Example:
class Article(models.Model):
author = models.ForeignKey('accounts.User')
editor = models.ForeignKey('accounts.User')
This will cause the error, because Django tries to automatically create a backwards relation for instances of accounts.User for each foreign key relation to user like user.article_set. This default method is ambiguous. Would user.article_set.all() refer to the user's articles related by the author field, or by the editor field?
Solution:
class Article(models.Model):
author = models.ForeignKey('accounts.User', related_name='author_article_set')
editor = models.ForeignKey('accounts.User', related_name='editor_article_set')
Now, for an instance of user user, there are two different manager methods:
user.author_article_set — user.author_article_set.all() will return a Queryset of all Article objects that have author == user
user.editor_article_set — user.editor_article_set.all() will return a Queryset of all Article objects that have editor == user
Note:
This is an old example — on_delete is now another required argument to models.ForeignKey. Details at What does on_delete do on Django models?
"If a model has a ForeignKey, instances of the foreign-key model will have access to a Manager that returns all instances of the first model. By default, this Manager is named FOO_set, where FOO is the source model name, lowercased."
But if you have more than one foreign key in a model, django is unable to generate unique names for foreign-key manager.
You can help out by adding "related_name" arguments to the foreignkey field definitions in your models.
See here:
https://docs.djangoproject.com/en/dev/topics/db/queries/#following-relationships-backward
If your models are inheriting from the same parent model, you should set a unique related_name in the parent's ForeignKey. For example:
author = models.ForeignKey('accounts.User', related_name='%(app_label)s_%(class)s_related')
It's better explained in th
If your models are inheriting from the same parent model, you should set a unique related_name in the parent's ForeignKey. For example:
author = models.ForeignKey('accounts.User', related_name='%(app_label)s_%(class)s_related')
It's better explained in the docs
I had a similar problem when I was trying to code a solution for a table that would pull names of football teams from the same table.
My table looked like this:
hometeamID = models.ForeignKey(Team, null=False, on_delete=models.CASCADE)
awayteamID = models.ForeignKey(Team, null=False, on_delete=models.CASCADE)
making the below changes solved my issue:
hometeamID = models.ForeignKey(Team, null=False, on_delete=models.CASCADE,related_name='home_team')
awayteamID = models.ForeignKey(Team, null=False, on_delete=models.CASCADE,related_name='away_team')
But in my case i am create a separate app for some functionality with same model name and field ( copy/paste ;) ) that's because of this type of error occurs i am just deleted the old model and code will work fine
May be help full for beginners like me :)
This isn't an ultimate answer for the question, however for someone it may solve the problem.
I got the same error in my project after checking out a really old commit (going to detached head state) and then getting the code base back up to date. Solution was to delete all *.pyc files in the project.
Do as the error message instructs you to:
Add a related_name argument to the
definition for 'creator'.