Re: Django Model related_name

2022-09-08 Thread Toshar Saini
when you want to fetch multiple objects from reverse relation(foriengkey)

On Tue, Sep 6, 2022 at 3:51 PM Justin Kpakpa  wrote:

> Hello, pls under what circumstances do you need to defined a related_name
> of a model field?
>
> --
> 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+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/63171f1d.170a0220.87ca8.aef5%40mx.google.com
> <https://groups.google.com/d/msgid/django-users/63171f1d.170a0220.87ca8.aef5%40mx.google.com?utm_medium=email_source=footer>
> .
>

-- 
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+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CA%2B_kdj%2B3z%3Drx1%2BQP-y5bUDJW5dPuAAHnUnXOM%3DDd0zbNoePHAw%40mail.gmail.com.


Re: Django Model related_name

2022-09-06 Thread DJANGO DEVELOPER
when you want to fetch multiple objects from that model ( having a foreign
key relation)

On Tue, Sep 6, 2022 at 3:21 PM Justin Kpakpa  wrote:

> Hello, pls under what circumstances do you need to defined a related_name
> of a model field?
>
> --
> 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+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/63171f1d.170a0220.87ca8.aef5%40mx.google.com
> <https://groups.google.com/d/msgid/django-users/63171f1d.170a0220.87ca8.aef5%40mx.google.com?utm_medium=email_source=footer>
> .
>

-- 
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+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAKPY9pkxaO3Gj9CZE7pwCchwe2kDhrazpZQYBOJjuM_BjH4ODA%40mail.gmail.com.


Django Model related_name

2022-09-06 Thread Justin Kpakpa
Hello, pls under what circumstances do you need to defined a related_name of a 
model field?

-- 
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+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/63171f1d.170a0220.87ca8.aef5%40mx.google.com.


Is the document not consistent for related_name?

2021-06-23 Thread ihc...@gmail.com
`%(model_name)s` is recommended in the document default_related_name 
<https://docs.djangoproject.com/en/3.2/ref/models/options/#default-related-name>
 
but `%(class)s ` is recommended in the document Be careful with 
related_name and related_query_name 
<https://docs.djangoproject.com/en/3.2/topics/db/models/#be-careful-with-related-name-and-related-query-name>
.

Is the document not consistent for related_name? Althought both are worked.

-- 
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+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/3a4a59b4-3c52-43ac-8fd8-3b161815cb84n%40googlegroups.com.


Re: Why are foreign keys rewritten when adding related_name?

2019-03-04 Thread Hanne Moa
No, 1.11. This project is still on Python 2.7 but I do think we'll
have it on Python 3(.5) before the year is over.

On Fri, 1 Mar 2019 at 21:16, Simon Charette  wrote:
>
> Hello HM,
>
> I know that some changes have been made to avoid unnecessary foreign key
> rebuilds on some option changes.
>
> Are you experiencing this on 2.1 and 2.2 pre release?
>
> Simon
>
> Le vendredi 1 mars 2019 02:40:01 UTC-5, HM a écrit :
>>
>> I added "related_name" to an exiting ForeignKey and checked with
>> "django-admin sqlmigrate" what would be done.
>>
>> It seems that the foreign key constraint is dropped, then the exact
>> same constraint is added back. Why?
>>
>> Example: If we have the classes:
>>
>> class Wall(models.Model):
>> ..
>>
>> class Door(models.Model):
>> ..wall = models.ForeignKey(Wall)
>>
>> and change Door.wall to models.ForeignKey(Wall, related_name='walls'), then:
>>
>> Prior to this, there exist (postgres) the constraint:
>>
>> "app_door_wall_id_45647_fk_app_wall" FOREIGN KEY (wall_id) REFERENCES
>> app_wall(id) DEFERRABLE INITIALLY DEFERRED.
>>
>> "django_admin sqlmigrate" reports:
>>
>> SET CONSTRAINTS "app_door_wall_id_45647_fk_app_wall" IMMEDIATE; ALTER
>> TABLE  "app_door" DROP CONSTRAINT
>> "app_door_wall_id_45647_fk_app_wall";
>> ALTER TABLE "app_door" ADD CONSTRAINT
>> "app_door_wall_id_45647_fk_app_wall" FOREIGN KEY ("wall_id")
>> REFERENCES "app_wall" ("id") DEFERRABLE INITIALLY DEFERRED;
>>
>> After running the migration, which is run as there's stuff in the log,
>> there exists seemingly the same constraint as before:
>>
>> "app_door_wall_id_45647_fk_app_wall" FOREIGN KEY (wall_id) REFERENCES
>> app_wall(id) DEFERRABLE INITIALLY DEFERRED.
>>
>> Why waste a connection this way?
>>
>> --
>> HM
>
> --
> 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+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at https://groups.google.com/group/django-users.
> To view this discussion on the web visit 
> https://groups.google.com/d/msgid/django-users/a1d9f7a9-be2a-41d5-8a43-4b468ad4a547%40googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.

-- 
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+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CACQ%3DrrcnDAs%2BK59__zo0aMp0Xfk_aOz5okq-Hn6aacSYM8Mntg%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Why are foreign keys rewritten when adding related_name?

2019-03-01 Thread Simon Charette
Hello HM,

I know that some changes have been made to avoid unnecessary foreign key
rebuilds on some option changes.

Are you experiencing this on 2.1 and 2.2 pre release?

Simon

Le vendredi 1 mars 2019 02:40:01 UTC-5, HM a écrit :
>
> I added "related_name" to an exiting ForeignKey and checked with 
> "django-admin sqlmigrate" what would be done. 
>
> It seems that the foreign key constraint is dropped, then the exact 
> same constraint is added back. Why? 
>
> Example: If we have the classes: 
>
> class Wall(models.Model): 
> .. 
>
> class Door(models.Model): 
> ..wall = models.ForeignKey(Wall) 
>
> and change Door.wall to models.ForeignKey(Wall, related_name='walls'), 
> then: 
>
> Prior to this, there exist (postgres) the constraint: 
>
> "app_door_wall_id_45647_fk_app_wall" FOREIGN KEY (wall_id) REFERENCES 
> app_wall(id) DEFERRABLE INITIALLY DEFERRED. 
>
> "django_admin sqlmigrate" reports: 
>
> SET CONSTRAINTS "app_door_wall_id_45647_fk_app_wall" IMMEDIATE; ALTER 
> TABLE  "app_door" DROP CONSTRAINT 
> "app_door_wall_id_45647_fk_app_wall"; 
> ALTER TABLE "app_door" ADD CONSTRAINT 
> "app_door_wall_id_45647_fk_app_wall" FOREIGN KEY ("wall_id") 
> REFERENCES "app_wall" ("id") DEFERRABLE INITIALLY DEFERRED; 
>
> After running the migration, which is run as there's stuff in the log, 
> there exists seemingly the same constraint as before: 
>
> "app_door_wall_id_45647_fk_app_wall" FOREIGN KEY (wall_id) REFERENCES 
> app_wall(id) DEFERRABLE INITIALLY DEFERRED. 
>
> Why waste a connection this way? 
>
> -- 
> HM 
>

-- 
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+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/a1d9f7a9-be2a-41d5-8a43-4b468ad4a547%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Why are foreign keys rewritten when adding related_name?

2019-02-28 Thread Hanne Moa
I added "related_name" to an exiting ForeignKey and checked with
"django-admin sqlmigrate" what would be done.

It seems that the foreign key constraint is dropped, then the exact
same constraint is added back. Why?

Example: If we have the classes:

class Wall(models.Model):
..

class Door(models.Model):
..wall = models.ForeignKey(Wall)

and change Door.wall to models.ForeignKey(Wall, related_name='walls'), then:

Prior to this, there exist (postgres) the constraint:

"app_door_wall_id_45647_fk_app_wall" FOREIGN KEY (wall_id) REFERENCES
app_wall(id) DEFERRABLE INITIALLY DEFERRED.

"django_admin sqlmigrate" reports:

SET CONSTRAINTS "app_door_wall_id_45647_fk_app_wall" IMMEDIATE; ALTER
TABLE  "app_door" DROP CONSTRAINT
"app_door_wall_id_45647_fk_app_wall";
ALTER TABLE "app_door" ADD CONSTRAINT
"app_door_wall_id_45647_fk_app_wall" FOREIGN KEY ("wall_id")
REFERENCES "app_wall" ("id") DEFERRABLE INITIALLY DEFERRED;

After running the migration, which is run as there's stuff in the log,
there exists seemingly the same constraint as before:

"app_door_wall_id_45647_fk_app_wall" FOREIGN KEY (wall_id) REFERENCES
app_wall(id) DEFERRABLE INITIALLY DEFERRED.

Why waste a connection this way?

-- 
HM

-- 
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+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CACQ%3DrrdbgWpcSgm85fDDskWNRXvYQ5hGyyo9yn5T5fyRj7%2BPQg%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Filter data in related_name loop

2017-10-11 Thread tango ward
Hi guys, I've been scratching my head on this one. I want to know if it's
possible to filter the data of models class with related_name in a foor
loop? Basically, I want to show the members info associated to a Team.

models.py

class Team_Region(models.Model):
name = models.CharField(max_length=50)


# String representation
def __str__(self):
return self.name





class Team_Name(models.Model):
team_name = models.CharField(max_length=150)
logo = models.ImageField(upload_to='team_logos', blank=True)
region_member = models.ForeignKey(Team_Region,
related_name='region_mem')


def __str__(self):
return self.team_name + ' - ' + str(self.region_member)




class Team_Member(models.Model):
member_name = models.CharField(max_length=150)
position = models.CharField(max_length=50)
member_of_team = models.ForeignKey(Team_Name, related_name='team_mem')


def __str__(self):
return self.member_name + ' - ' + str(self.member_of_team)


views.py

# Listview of Regions
class TeamRegionListView(ListView):
context_object_name = 'region_name'
model = Team_Region
template_name = 'dota_teams/team_region_list.html'



# DetailView of Regions
class TeamRegionDetailView(DetailView):
context_object_name = 'team_names'
model = Team_Region
template_name = 'dota_teams/team_region_detail.html'



# DetailView of Teams. Will show team members
class TeamDetailView(DetailView):
context_object_name = 'team_members'
model = Team_Region
template_name = 'dota_teams/team_detail.html'

urls.py

url(r'^$', views.TeamRegionListView.as_view(), name='region_list'),
url(r'^(?P\d+)/$', views.TeamRegionDetailView.as_view(),
name='region_detail'),
url(r'^(?P\d+)/(\d+)/$', views.TeamDetailView.as_view(),
name='team_detail'),


Problem is, in my team_detail.html, for me to access the members' info, I
have these loops:


{% for team in team_members.region_mem.all %}
{% for member in team.team_mem.all %}


{{ member.member_name }}


{{ member.position }}



{% endfor %}
{% endfor %}


All members info will appear if i click a team which is not the way I want
it. I only want to show the members info associated to a team that I
clicked. This happens because I hae the team.team_mem.all in my loop which
basically shows all members data including those who are not part of the
team. Is there a way to filter this? My apologies for the long email.


TIA,
jarvis

-- 
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+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAA6wQLKCC1duXTRdru67Ej0MyuvMKL17DM4QTh%2BBmxxsw%2BxeFQ%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


related_name for two models which have same name but belong to different app

2016-11-28 Thread Xueguang Yang
Hi:

I am a little confused about this section of django official docs: Be 
careful with related_name 
<https://docs.djangoproject.com/en/1.9/topics/db/models/#be-careful-with-related-name>

when you are using related_name in an abstract base class (only), part of 
> the name should contain '%(app_label)s' and '%(class)s'.
>

However, if related_name only containe '%(class)' is still OK if there 
isn't two models which have the same name. In this case, if I define a new 
model that it's name conflict to a existing model, it can not pass 
the inspection when run makemigrations command. I'll show you a simple 
example similar to example in official docs.

common/models.py

from django.db import models

class Base(models.Model):
m2m = models.ManyToManyField(OtherModel, related_name="%(class)s_related")

class Meta:
abstract = True


app1/models.py

from django,db import models
from common,models import Base

class Child(Base):
   pass

app2/models.py

from django,db import models
from common,models import Base

class Child(Base):
   pass

This would raise an exception when run makemigrations command because two 
child model in different apps have the same related_name: child_related.

However, if I delete app2, migrate process would be OK. Then I create app2 
add the those codes again, Exception would raised. Though I explicitly 
assign a default_related_name in Meta option for Child model in app2, it 
can't solve the problem.

It seems we have to change the source code in Base model such as add a 
'%(app_label)' part for related_name, but everything in app1 need change 
too.

So why doesn't django force developer to add %(class) and %(app_label) even 
there are no conflicts for all models. Because if don't,  though there is 
no conflict now, it still has a potential conflict in the future.

-- 
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+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/f109494e-ea45-4eb4-b6af-3fc80376b81f%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: ManyToManyField('self') not using related_name

2016-07-19 Thread Farhan Khan
The solution was that I needed to set symmetrical=False, per the 
documentation 
here: 
https://docs.djangoproject.com/en/1.9/ref/models/fields/#django.db.models.ManyToManyField.symmetrical

On Tuesday, July 19, 2016 at 2:52:16 PM UTC-4, Farhan Khan wrote:
>
> I am using a ManyToManyField whose target is a 'self' reference, but it 
> does not create a related_name "reverse" field.
>
> Here is my model:
>
> class SecurityGroup(models.Model):
> name = models.CharField(max_length=100) 
> description = models.TextField() 
> subgroups = models.ManyToManyField('self', related_name='origin') 
>
> def __str__(self): 
>
> return self.name
>
>
> And here is the problem:
>
>
> >>> x = SecurityGroup(name='name', description='description')
> >>> x.save()
> >>> x.origin()
> Traceback (most recent call last):
>   File "", line 1, in 
> AttributeError: 'SecurityGroup' object has no attribute 'origin'
>
>
> There also no x.securitygroup_set. Is this a bug?
>
>
>
>

-- 
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+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/8076eb42-3604-43ad-aec2-94d04d0c6602%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


ManyToManyField('self') not using related_name

2016-07-19 Thread Farhan Khan
I am using a ManyToManyField whose target is a 'self' reference, but it 
does not create a related_name "reverse" field.

Here is my model:

class SecurityGroup(models.Model):
name = models.CharField(max_length=100) 
description = models.TextField() 
subgroups = models.ManyToManyField('self', related_name='origin') 

def __str__(self): 

return self.name


And here is the problem:


>>> x = SecurityGroup(name='name', description='description')
>>> x.save()
>>> x.origin()
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'SecurityGroup' object has no attribute 'origin'


There also no x.securitygroup_set. Is this a bug?



-- 
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+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/9a8d0c8c-9429-4340-be69-78b8e6a5a296%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: The related_name of ForeignKey cannot be Unicode name after Django 1.8

2015-06-22 Thread Cheng-Hung Hsueh
I have posted in https://code.djangoproject.com/ticket/25016#ticket .

Tim Graham於 2015年6月23日星期二 UTC+8上午12時30分48秒寫道:
>
> It looks like the check added in ticket #22064 may be too strict (only 
> allowing alphanumeric characters in related_name). Would you like to open a 
> ticket?
>
> On Monday, June 22, 2015 at 11:28:50 AM UTC-4, Cheng-Hung Hsueh wrote:
>>
>> This code can run before django 1.7
>> But "related_name" got an error after django 1.8
>>
>> 使用者表.來源: (fields.E306) The name '使用者' is invalid related_name for field 
>> 使用者表.來源
>>
>>
>> class 來源表(models.Model):
>> 名 = models.CharField(max_length=100)
>>
>> class 使用者表(models.Model):
>> 來源 = models.OneToOneField(來源表, related_name='使用者', primary_key=True, 
>> null=False)
>>
>>
>> Is it a bug? I know adding many checks in Django 1.8
>>
>

-- 
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+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@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/1b762fd2-3fea-480b-9d60-535adafb4209%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: The related_name of ForeignKey cannot be Unicode name after Django 1.8

2015-06-22 Thread Tim Graham
It looks like the check added in ticket #22064 may be too strict (only 
allowing alphanumeric characters in related_name). Would you like to open a 
ticket?

On Monday, June 22, 2015 at 11:28:50 AM UTC-4, Cheng-Hung Hsueh wrote:
>
> This code can run before django 1.7
> But "related_name" got an error after django 1.8
>
> 使用者表.來源: (fields.E306) The name '使用者' is invalid related_name for field 
> 使用者表.來源
>
>
> class 來源表(models.Model):
> 名 = models.CharField(max_length=100)
>
> class 使用者表(models.Model):
> 來源 = models.OneToOneField(來源表, related_name='使用者', primary_key=True, 
> null=False)
>
>
> Is it a bug? I know adding many checks in Django 1.8
>

-- 
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+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@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/279ee276-297d-4b40-afe3-917167ffaf44%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


The related_name of ForeignKey cannot be Unicode name after Django 1.8

2015-06-22 Thread Cheng-Hung Hsueh
This code can run before django 1.7
But "related_name" got an error after django 1.8

使用者表.來源: (fields.E306) The name '使用者' is invalid related_name for field 
使用者表.來源


class 來源表(models.Model):
名 = models.CharField(max_length=100)

class 使用者表(models.Model):
來源 = models.OneToOneField(來源表, related_name='使用者', primary_key=True, 
null=False)


Is it a bug? I know adding many checks in Django 1.8

-- 
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+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@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/453092fc-deca-422b-a405-e32ad3b41b1a%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Backwards relation not showing up via related_name in inherited models

2013-10-28 Thread Daniel Roseman
On Monday, 28 October 2013 15:11:24 UTC, Joshua Orvis wrote:

> Thank you for responding, that's extremely helpful.  I'm still failing to 
> query against it though.  How would I implement a query for the 
> get_children() method in the example above?  That is, for any given 
> instance of FlowBlueprint how do I get all objects with a relation to it?
>

The point is that unless the M2M field has `symmetrical=False`, there's 
only one side of the relation, which is `parents`. So in this case you 
would just do `self.parents.all()`. That said, for a parent/child 
relationship like this you probably do want to set symmetrical to False, in 
which case `self.children.all()` would work.
--
DR.

-- 
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+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@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/e90e7e9e-8426-4e20-95df-807edabc18f9%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Backwards relation not showing up via related_name in inherited models

2013-10-28 Thread Joshua Orvis
Thank you for responding, that's extremely helpful.  I'm still failing to 
query against it though.  How would I implement a query for the 
get_children() method in the example above?  That is, for any given 
instance of FlowBlueprint how do I get all objects with a relation to it?

On Monday, October 28, 2013 6:56:40 AM UTC-5, Daniel Roseman wrote:
>
> On Monday, 28 October 2013 07:29:39 UTC, Joshua Orvis wrote:
>
>> I'm using Django 1.6 RC1 and Python 3.3 with the following models:
>>
>> class StepBlueprint(models.Model):
>> parents = models.ManyToManyField('self', blank=True, null=True, 
>> related_name='children')
>> name   = models.CharField( max_length=100 )
>>
>> def __str__(self):
>> return self.name
>>
>> class FlowBlueprint(StepBlueprint):
>> description = models.TextField()
>> 
>> def get_children(self):
>> print("DEBUG: processing ({0})".format(self))
>> print(dir(self))
>>
>> # why isn't this working??  this is what related_name is supposed 
>> to provide
>> return self.children
>>
>> When I call get_children() here, I get the following:
>>
>> DEBUG: processing (Prodigal)
>> ['DoesNotExist', 'MultipleObjectsReturned', 'TYPES', '__class__', 
>> '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', 
>> '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', 
>> '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', 
>> '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 
>> '__weakref__', '_base_manager', '_default_manager', '_deferred', 
>> '_do_insert', '_do_update', '_get_FIELD_display', 
>> '_get_next_or_previous_by_FIELD', '_get_next_or_previous_in_order', 
>> '_get_pk_val', '_get_unique_checks', '_meta', '_perform_date_checks', 
>> '_perform_unique_checks', '_save_parents', '_save_table', '_set_pk_val', 
>> '_state', 'build', 'clean', 'clean_fields', 'commandblueprint', 
>> 'conditional_code', 'date_error_message', 'delete', 'description', 
>> 'flow_set', 'flowblueprint', 'full_clean', 'get_children', 'get_command', 
>> 'get_type_display', 'id', 'name', 'objects', 'parents', 'pk', 
>> 'prepare_database_save', 'save', 'save_base', 'serializable_value', 
>> 'standalonetool_set', 'stepblueprint_ptr', 'stepblueprint_ptr_id', 'type', 
>> 'unique_error_message', 'validate_unique']
>> Traceback (most recent call last):
>>   [ call stack ... ]
>> return self.children
>> AttributeError: 'FlowBlueprint' object has no attribute 'children'
>>
>> What am I doing wrong here?  From within the FlowBlueprint object I want 
>> to be able to get the backwards relation of all those objects pointing to 
>> it, and it seems like related_name is supposed to provide that.  Its value 
>> doesn't show up in the dir() output.
>>
>> Any help would be greatly appreciated.
>>
>
>
> This has nothing to do with inheritance - you would get the same result if 
> you called `self.children` from StepBlueprint.
>
> See the documentation on many-to-many relationships with self:
>
> https://docs.djangoproject.com/en/1.5/ref/models/fields/#django.db.models.ManyToManyField.symmetrical
> (emphasis added):
>
> "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."
> --
> DR.
>

-- 
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+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@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/66e5ec75-040b-4c36-85da-85af7365e9f2%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Backwards relation not showing up via related_name in inherited models

2013-10-28 Thread Daniel Roseman
On Monday, 28 October 2013 07:29:39 UTC, Joshua Orvis wrote:

> I'm using Django 1.6 RC1 and Python 3.3 with the following models:
>
> class StepBlueprint(models.Model):
> parents = models.ManyToManyField('self', blank=True, null=True, 
> related_name='children')
> name   = models.CharField( max_length=100 )
>
> def __str__(self):
> return self.name
>
> class FlowBlueprint(StepBlueprint):
> description = models.TextField()
> 
> def get_children(self):
> print("DEBUG: processing ({0})".format(self))
> print(dir(self))
>
> # why isn't this working??  this is what related_name is supposed 
> to provide
> return self.children
>
> When I call get_children() here, I get the following:
>
> DEBUG: processing (Prodigal)
> ['DoesNotExist', 'MultipleObjectsReturned', 'TYPES', '__class__', 
> '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', 
> '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', 
> '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', 
> '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 
> '__weakref__', '_base_manager', '_default_manager', '_deferred', 
> '_do_insert', '_do_update', '_get_FIELD_display', 
> '_get_next_or_previous_by_FIELD', '_get_next_or_previous_in_order', 
> '_get_pk_val', '_get_unique_checks', '_meta', '_perform_date_checks', 
> '_perform_unique_checks', '_save_parents', '_save_table', '_set_pk_val', 
> '_state', 'build', 'clean', 'clean_fields', 'commandblueprint', 
> 'conditional_code', 'date_error_message', 'delete', 'description', 
> 'flow_set', 'flowblueprint', 'full_clean', 'get_children', 'get_command', 
> 'get_type_display', 'id', 'name', 'objects', 'parents', 'pk', 
> 'prepare_database_save', 'save', 'save_base', 'serializable_value', 
> 'standalonetool_set', 'stepblueprint_ptr', 'stepblueprint_ptr_id', 'type', 
> 'unique_error_message', 'validate_unique']
> Traceback (most recent call last):
>   [ call stack ... ]
> return self.children
> AttributeError: 'FlowBlueprint' object has no attribute 'children'
>
> What am I doing wrong here?  From within the FlowBlueprint object I want 
> to be able to get the backwards relation of all those objects pointing to 
> it, and it seems like related_name is supposed to provide that.  Its value 
> doesn't show up in the dir() output.
>
> Any help would be greatly appreciated.
>


This has nothing to do with inheritance - you would get the same result if 
you called `self.children` from StepBlueprint.

See the documentation on many-to-many relationships with self:
https://docs.djangoproject.com/en/1.5/ref/models/fields/#django.db.models.ManyToManyField.symmetrical
(emphasis added):

"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."
--
DR.

-- 
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+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@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/b2760ab2-e7bf-4733-84a7-36281705cf8c%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.


Backwards relation not showing up via related_name in inherited models

2013-10-28 Thread Joshua Orvis
I'm using Django 1.6 RC1 and Python 3.3 with the following models:

class StepBlueprint(models.Model):
parents = models.ManyToManyField('self', blank=True, null=True, 
related_name='children')
name   = models.CharField( max_length=100 )

def __str__(self):
return self.name

class FlowBlueprint(StepBlueprint):
description = models.TextField()

def get_children(self):
print("DEBUG: processing ({0})".format(self))
print(dir(self))

# why isn't this working??  this is what related_name is supposed 
to provide
return self.children

When I call get_children() here, I get the following:

DEBUG: processing (Prodigal)
['DoesNotExist', 'MultipleObjectsReturned', 'TYPES', '__class__', 
'__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', 
'__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', 
'__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', 
'__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 
'__weakref__', '_base_manager', '_default_manager', '_deferred', 
'_do_insert', '_do_update', '_get_FIELD_display', 
'_get_next_or_previous_by_FIELD', '_get_next_or_previous_in_order', 
'_get_pk_val', '_get_unique_checks', '_meta', '_perform_date_checks', 
'_perform_unique_checks', '_save_parents', '_save_table', '_set_pk_val', 
'_state', 'build', 'clean', 'clean_fields', 'commandblueprint', 
'conditional_code', 'date_error_message', 'delete', 'description', 
'flow_set', 'flowblueprint', 'full_clean', 'get_children', 'get_command', 
'get_type_display', 'id', 'name', 'objects', 'parents', 'pk', 
'prepare_database_save', 'save', 'save_base', 'serializable_value', 
'standalonetool_set', 'stepblueprint_ptr', 'stepblueprint_ptr_id', 'type', 
'unique_error_message', 'validate_unique']
Traceback (most recent call last):
  [ call stack ... ]
return self.children
AttributeError: 'FlowBlueprint' object has no attribute 'children'

What am I doing wrong here?  From within the FlowBlueprint object I want to 
be able to get the backwards relation of all those objects pointing to it, 
and it seems like related_name is supposed to provide that.  Its value 
doesn't show up in the dir() output.

Any help would be greatly appreciated.

-- 
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+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@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/6ae3bcd5-ebc1-4284-a3b8-f4c2866a9b0b%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.


Re: My poll doesn't work when I start using related_name, help please.

2013-08-17 Thread Pepsodent Cola
Yay, it worked!  Thank you Dr. Roseman.  :)

*[SOLVED]*
*
*



On Friday, August 16, 2013 4:51:36 PM UTC+2, Daniel Roseman wrote:
>
> On Friday, 16 August 2013 14:06:38 UTC+1, Pepsodent Cola wrote:
>
>> ### PART A
>>
>> My altword_list template file receives a primary key ID from my Index 
>> template file.
>>
>> #___
>> *altword_list.html*
>>
>> {{ poll.rosword }}
>> {% if error_message %}{{ error_message }}{% endif 
>> %}
>>
>> Filter 5
>> 
>> *{% for choice in poll.altword_set.all %}*
>> 
>> *{{ choice.rosword }}*  = {{ choice.votes }} votes
>> {% endfor %}
>> 
>>
>> #___
>>
>>
>>
>> ### PART B
>>
>> * Things work as intended when the rosword field just contain a simple 
>> "FK(Word)".
>> * But when I use the other rosword field instead containing "FK(Word, 
>> related_name='altword_rosword')", then
>>   my altword_list template file doesn't receive a primary key ID from my 
>> Index template file anymore.
>>
>> What am I doing wrong when using related_name in my rosword field?
>>
>> #___
>>
>> class Altword(models.Model):
>> #rosword = models.ForeignKey(Word, related_name='altword_rosword') *# 
>> altword_list.html doesn't receive pk ID anymore why?*
>> *rosword = models.ForeignKey(Word) # OK*
>> alt_ros_word = models.CharField(max_length=200)
>> #wordy = models.OneToOneField(Word, related_name='wordy', 
>> primary_key=True)
>> votes = models.IntegerField(default=0)
>>
>> def __unicode__(self):
>> return self.alt_ros_word
>>
>> #___
>>
>>
> I have no idea what "primary key ID" has to do with anything. However, if 
> you've changed the related name in the field, you should change it in the 
> template as well:
>
>   {% for choice in poll.altword_rosword.all %}
> --
> DR.
>

-- 
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+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
For more options, visit https://groups.google.com/groups/opt_out.


Re: My poll doesn't work when I start using related_name, help please.

2013-08-16 Thread Daniel Roseman
On Friday, 16 August 2013 14:06:38 UTC+1, Pepsodent Cola wrote:

> ### PART A
>
> My altword_list template file receives a primary key ID from my Index 
> template file.
>
> #___
> *altword_list.html*
>
> {{ poll.rosword }}
> {% if error_message %}{{ error_message }}{% endif 
> %}
>
> Filter 5
> 
> *{% for choice in poll.altword_set.all %}*
> 
> *{{ choice.rosword }}*  = {{ choice.votes }} votes
> {% endfor %}
> 
>
> #___
>
>
>
> ### PART B
>
> * Things work as intended when the rosword field just contain a simple 
> "FK(Word)".
> * But when I use the other rosword field instead containing "FK(Word, 
> related_name='altword_rosword')", then
>   my altword_list template file doesn't receive a primary key ID from my 
> Index template file anymore.
>
> What am I doing wrong when using related_name in my rosword field?
>
> #___
>
> class Altword(models.Model):
> #rosword = models.ForeignKey(Word, related_name='altword_rosword') *# 
> altword_list.html doesn't receive pk ID anymore why?*
> *rosword = models.ForeignKey(Word) # OK*
> alt_ros_word = models.CharField(max_length=200)
> #wordy = models.OneToOneField(Word, related_name='wordy', 
> primary_key=True)
> votes = models.IntegerField(default=0)
>
> def __unicode__(self):
> return self.alt_ros_word
>
> #___
>
>
I have no idea what "primary key ID" has to do with anything. However, if 
you've changed the related name in the field, you should change it in the 
template as well:

  {% for choice in poll.altword_rosword.all %}
--
DR.

-- 
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+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
For more options, visit https://groups.google.com/groups/opt_out.


My poll doesn't work when I start using related_name, help please.

2013-08-16 Thread Pepsodent Cola
### PART A

My altword_list template file receives a primary key ID from my Index 
template file.
#___
*altword_list.html*

{{ poll.rosword }}
{% if error_message %}{{ error_message }}{% endif %}

Filter 5

*{% for choice in poll.altword_set.all %}*

*{{ choice.rosword }}*  = {{ choice.votes }} votes
{% endfor %}

#___



### PART B

* Things work as intended when the rosword field just contain a simple 
"FK(Word)".
* But when I use the other rosword field instead containing "FK(Word, 
related_name='altword_rosword')", then
  my altword_list template file doesn't receive a primary key ID from my 
Index template file anymore.

What am I doing wrong when using related_name in my rosword field?
#___

class Altword(models.Model):
#rosword = models.ForeignKey(Word, related_name='altword_rosword') *# 
altword_list.html doesn't receive pk ID anymore why?*
*rosword = models.ForeignKey(Word) # OK*
alt_ros_word = models.CharField(max_length=200)
#wordy = models.OneToOneField(Word, related_name='wordy', 
primary_key=True)
votes = models.IntegerField(default=0)

def __unicode__(self):
return self.alt_ros_word
#___

-- 
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+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Model with several ManyToManyFields - related_name problem

2011-03-18 Thread George Lund
Hiya, thanks for the reply.

So in this case the extra fields are actually denormalized subsets of the 
original field, and the reverse relation can use the main field.  (At least, 
at the moment, that's my plan, but that could change.  Which I guess goes to 
show how rare this case probably actually is.)

But you can see that with the data being so similar on each many-to-many 
table, I'd want to avoid confusing the other model with a set of extra 
properties that aren't so useful and will have similar names!  So I guess 
there might be other cases where you likewise didn't want to create a 
confusing backwards relation, and the '+' behaviour might be expected to 
work as the documentation suggests (to me) that it might.

Incidentally I'm a bit confused about the naming of ManyToMany fields: the 
examples tend to name them in the plural
sites = models.ManyToManyField(Site, verbose_name="list of sites")
but the backwards relation gets created with a singular name (inevitably I 
guess, because that's what the system can work out).  It seems a bit 
inconsistent?

cheers
George

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Model with several ManyToManyFields - related_name problem

2011-03-17 Thread werefr0g

Hello,

I believe you need related_name, for disambiguation at least. Maybe by 
setting a db_table you can bypass the related_name but I'm not convinced.


Actually, I'm "parasiting" your post to ask when "[we]'d prefer Django 
didn't create a backwards relation"?


Regards,

--
You received this message because you are subscribed to the Google Groups "Django 
users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Model with several ManyToManyFields - related_name problem

2011-03-17 Thread George Lund
I have a model with more than one (3 in fact) ManyToManyFields which
point to the same other model.

As long as I specify distinct related_names for each, all is well.

But the documentation [1] suggests that if I don't need the backwards
relation, then specifying '+' as the related_name should work.  But I
don't seem to be able to specify '+' for more than one of the fields:
I get a 'reverse query clashes' error.

Is this expected?  It feels like a bug (i.e. I'd expect all fields
with related_name="+" to be ignored for this check).

TIA

George


[1: 
http://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.related_name
]

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: pass related_name-s into Model.objects.create()?

2010-05-18 Thread Phlip
> > But what about 'ForeignKey's? May we pass their 'remote_name's in with
> > the kwargs?
>
> Foreign Keys - yes. Reverse Foreign Keys - no.

Point: All kwargs takes is the fields on this object.

> In the case of a foreign key, just pass in the object instance that
> you want your object to be related to (e.g., when creating a Question
> object, you can pass in the Poll that the question belongs to).
>
> > If not, what's some clean way to construct everything all at once?
>
> Depends on what you mean by "at once".

I want to take out the objects.create, and create everything in
memory. So the many-to-ones - the foreign keys - go in the kwargs.

  o = Model(field=x, foreigner=Foreigner())
  o.manys = [ Item(), Item(), Item() ]

Now everything hangs in memory like it would in the database if we
created all of it.

Then I want o.save() to blast it all into the database.

> If you're trying to assign a list of related objects, that isn't a
> single operation either - what you're actually doing is setting a
> foreign key value on multiple related objects.

No prob - I will just create the Item() things with a foreign key to
their parent, and leave the syntactic sugar.

Then I will call save() on everything from top to bottom, so all the
pks populate correctly.

> However, all of these are just wrappers around multiple underlying
> database calls. The changes won't happen "at once" unless you start
> getting involved with transactions etc.

I prematurely optimize so infrequently I forgot some people use it to
mean "in one database call". I just meant in one big humongous
statement. No prob.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: pass related_name-s into Model.objects.create()?

2010-05-18 Thread Russell Keith-Magee
On Tue, May 18, 2010 at 12:45 PM, Phlip  wrote:
> Djangoists:
>
> The documentation for Model.objects.create(**kwargs) does not define
> kwargs. It just sez "kwargs".
>
> I think all of our experiences would bear out "kwargs" may at least be
> the model's fields.

Correct.

> But what about 'ForeignKey's? May we pass their 'remote_name's in with
> the kwargs?

Foreign Keys - yes. Reverse Foreign Keys - no.

In the case of a foreign key, just pass in the object instance that
you want your object to be related to (e.g., when creating a Question
object, you can pass in the Poll that the question belongs to).

> If not, what's some clean way to construct everything all at once?

Depends on what you mean by "at once". As soon as you're dealing with
foreign keys, you're dealing with more than one database operation -
at the very least, you'll need to create or find the related objects.

If you're trying to assign a list of related objects, that isn't a
single operation either - what you're actually doing is setting a
foreign key value on multiple related objects. Django doesn't provide
a single wrapper call to create *and* assign reverse foreign key
relations, but if you really want one, it won't be too hard to write.

However, all of these are just wrappers around multiple underlying
database calls. The changes won't happen "at once" unless you start
getting involved with transactions etc.

Yours,
Russ Magee %-)

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



pass related_name-s into Model.objects.create()?

2010-05-17 Thread Phlip
Djangoists:

The documentation for Model.objects.create(**kwargs) does not define
kwargs. It just sez "kwargs".

I think all of our experiences would bear out "kwargs" may at least be
the model's fields.

But what about 'ForeignKey's? May we pass their 'remote_name's in with
the kwargs?

If not, what's some clean way to construct everything all at once?

--
  Phlip
  http://c2.com/cgi/wiki?ZeekLand

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



pass related_name-s into Model.objects.create()?

2010-05-17 Thread Phlip
Djangoids:

The documentation for Model.objects.create(**kwargs) just sez
"**kwargs".

What goes in the kwargs? Anything beside the obvious - the scalar
members of the model?

How about one-to-many relationships? Can I do this:

  Author.objects.create( name='Cromskey',
 blogs=[ b1, b2,
   Blog.objects.create(title='yack
yack yack') ] )

In my hypothetical kwargs, the related_name accepts an array of the
target models.

Do the kwargs support this convenience? Or must I simply plug the
items in the old-fashioned way, after they are created?

--
  Phlip
  http://c2.com/cgi/wiki?ZeekLand

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Abstract class related_name deppendent from application

2010-02-16 Thread gentlestone
Hi everyone,

I have an abstract base class which has foreign key. Derived classes
should have a related_name="%(class)s..." But, what if I have two or
more derived classes with the same name in different applications?
What is the solution of this issue?

Patch this piece of code in db/models/fields/related.py?

if not cls._meta.abstract and self.rel.related_name:
self.rel.related_name = self.rel.related_name % {'class':
cls.__name__.lower()}

How? Or there is some more elegant solution?

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Problem with ManyToMany Relationship and related_name

2010-01-14 Thread HWM-Rocker
Hi,

I am relatively new with Django but I like what I have seen so far.

why does this not work?

class Tag(models.Model):
text = models.CharField(max_length=200)
children = models.ManyToManyField('self', blank=True, null=True,
symmetrical=True, related_name='parents')
synonyms = models.ManyToManyField('self', blank=True, null=True)

What i want is a symmetrical link to the same project, like a linked
list with the difference that these is a many to many relationship.
Since there is also something like synonyms treebear and mptt are not
usefull for me.

Is there another possibility to achieve this. i thought about to
create a second element called parents and overwrite the add function
for them. To guarantee that there is a symmetrical. but i don't know
how to pass it trough, do i have to check if it is already in the
other before i add to prevent infinite loop or is there a better to do
it?

Thanks for your Help
-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.




Re: Django and related_name

2009-07-29 Thread Asinox

Thanks, guys im sorry Ramiro, something bother you?, im sorry.

i think the problem with the indentation is the copy/paste  in case of
wrong indentation django/python show error's.


Yes Mike is a decimal :(


On Jul 29, 9:54 pm, Ramiro Morales <cra...@gmail.com> wrote:
> On Wed, Jul 29, 2009 at 6:23 PM, Asinox<asi...@gmail.com> wrote:
>
> > Hi guys, first im so sorry with my english, im new with Django, u
> > know ;)
>
> > I have a problem with a related_name, the tables are fine, but the
> > problem is that in the Select (DropDown) the data display is "bad", in
> > this way: Tarifas_object:
>
> > Html code:
>
> > Tarifas object
>
> > how ill display the correct data?
>
> > my model:
>
> > [lots of ugly code snipped]
>
> Firstly, the fact that English isn't your native language (it isn't mine
> either) doesn't mean it is fine to use thinks like "u" instead of you,
> it's basically a matter of respect for the people that will read your
> message.
>
> Second, you don't need to paste your entire models, trim them
> to the field that are relevant to question you are asking, there
> is no point in subjecting the reader (potentially wanting
> to help you) to wade through  many irrelevant lines of code, Also,
> the code you pasted seems to have very bad indentation, I don't
> know if that's an artifact from your copy/paste operation or
> real problems.
>
> One of these formatting/indentation errors could explain
> the problem you describe:
>
> > def __inicode__(self):
> >    return self.precio
>
> This isn' t correctly indented to be considered a method of your
> Tarifas model, it is being interpreted as a module level
> function.  Obviously, the name is wrong too, it should be
> __unicode__
>
> Regards,
>
> --
> Ramiro Moraleshttp://rmorales.net
>
> PyCon 2009 Argentina - Vie 4 y Sab 5 Septiembre
> Buenos Aires, Argentinahttp://ar.pycon.org/2009/about/
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Django and related_name

2009-07-29 Thread Ramiro Morales

On Wed, Jul 29, 2009 at 6:23 PM, Asinox<asi...@gmail.com> wrote:
>
> Hi guys, first im so sorry with my english, im new with Django, u
> know ;)
>
> I have a problem with a related_name, the tables are fine, but the
> problem is that in the Select (DropDown) the data display is "bad", in
> this way: Tarifas_object:
>
> Html code:
>
> Tarifas object
>
> how ill display the correct data?
>
> my model:
>
> [lots of ugly code snipped]

Firstly, the fact that English isn't your native language (it isn't mine
either) doesn't mean it is fine to use thinks like "u" instead of you,
it's basically a matter of respect for the people that will read your
message.

Second, you don't need to paste your entire models, trim them
to the field that are relevant to question you are asking, there
is no point in subjecting the reader (potentially wanting
to help you) to wade through  many irrelevant lines of code, Also,
the code you pasted seems to have very bad indentation, I don't
know if that's an artifact from your copy/paste operation or
real problems.

One of these formatting/indentation errors could explain
the problem you describe:

> def __inicode__(self):
>return self.precio

This isn' t correctly indented to be considered a method of your
Tarifas model, it is being interpreted as a module level
function.  Obviously, the name is wrong too, it should be
__unicode__

Regards,

-- 
Ramiro Morales
http://rmorales.net

PyCon 2009 Argentina - Vie 4 y Sab 5 Septiembre
Buenos Aires, Argentina
http://ar.pycon.org/2009/about/

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Django and related_name

2009-07-29 Thread Mike Dewhirst

Asinox wrote:
> 
> 
> Hi guys, first im so sorry with my english, im new with Django, u
> know ;)
> 
> I have a problem with a related_name, the tables are fine, but the
> problem is that in the Select (DropDown) the data display is "bad", in
> this way: Tarifas_object:
> 
> Html code:
> 
> Tarifas object
> 
> how ill display the correct data?
> 
> my model:
> 
> class Tarifas(models.Model): recarga = models.CharField(max_length=7,
> help_text='Codigo de la tarifa')
>  precio = models.DecimalField(max_digits=7, decimal_places=2)
>  diligencias =  models.PositiveIntegerField(max_length=3)
> 

Is this a typo or is there such an attribute recognised by Django when 
you want to represent a decimal field?

> def __inicode__(self):



> return self.precio
> 
> class Meta:
> verbose_name_plural="Tarifas"
> 
> class Recarga(models.Model): socio = models.ForeignKey(User)
>  fecha = models.DateField(auto_now_add=True)
>   #valor = models.DecimalField(max_digits=6,
> decimal_places=2,verbose_name='Valor de la recarga', help_text=
> "Introduzca valores numericos ej.: 150.00")
>  valor = models.ForeignKey(Tarifas,
> related_name='recarga_valor')
>  diligencias = models.IntegerField(max_length=3,
> verbose_name='Cantidad de diligencias recargadas')
>  tiponcf = models.IntegerField(max_length=1,choices=TIPO_NCF,
> verbose_name='Tipo de comprobante fiscal')
>  ncf = models.CharField(max_length=19,verbose_name='Numero de
> comprobante fiscal')
>  cajero = models.CharField(max_length=20)
>  tipotarj = models.CharField(choices=TIPOS_TARJETAS,
> max_length=20, verbose_name='Tipo de tarjeta')
>  numtarj = models.IntegerField(max_length=16,
> verbose_name='Numero de tarjeta')
>  seguridad = models.IntegerField(max_length=3)
>  forma_pago = models.CharField(max_length=10,
> verbose_name='Forma de pago')
>  banco = models.CharField(max_length=20)
>  numerock = models.IntegerField(max_length=8,
> verbose_name='Numero de cheque')
> 
> def __unicode__(self):
> return u'%s %s %s %s' % (self.socio,self.diligencias, self.fecha)
> 
> 
> class Meta:
> ordering = ['socio']
> 
> Thanks guys.
> 
> > 
> 
> 


--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Django and related_name

2009-07-29 Thread Asinox



Hi guys, first im so sorry with my english, im new with Django, u
know ;)

I have a problem with a related_name, the tables are fine, but the
problem is that in the Select (DropDown) the data display is "bad", in
this way: Tarifas_object:

Html code:

Tarifas object

how ill display the correct data?

my model:

class Tarifas(models.Model): recarga = models.CharField(max_length=7,
help_text='Codigo de la tarifa')
 precio = models.DecimalField(max_digits=7, decimal_places=2)
 diligencias =  models.PositiveIntegerField(max_length=3)

def __inicode__(self):
return self.precio

class Meta:
verbose_name_plural="Tarifas"

class Recarga(models.Model): socio = models.ForeignKey(User)
 fecha = models.DateField(auto_now_add=True)
  #valor = models.DecimalField(max_digits=6,
decimal_places=2,verbose_name='Valor de la recarga', help_text=
"Introduzca valores numericos ej.: 150.00")
 valor = models.ForeignKey(Tarifas,
related_name='recarga_valor')
 diligencias = models.IntegerField(max_length=3,
verbose_name='Cantidad de diligencias recargadas')
 tiponcf = models.IntegerField(max_length=1,choices=TIPO_NCF,
verbose_name='Tipo de comprobante fiscal')
 ncf = models.CharField(max_length=19,verbose_name='Numero de
comprobante fiscal')
 cajero = models.CharField(max_length=20)
 tipotarj = models.CharField(choices=TIPOS_TARJETAS,
max_length=20, verbose_name='Tipo de tarjeta')
 numtarj = models.IntegerField(max_length=16,
verbose_name='Numero de tarjeta')
 seguridad = models.IntegerField(max_length=3)
 forma_pago = models.CharField(max_length=10,
verbose_name='Forma de pago')
 banco = models.CharField(max_length=20)
 numerock = models.IntegerField(max_length=8,
verbose_name='Numero de cheque')

def __unicode__(self):
return u'%s %s %s %s' % (self.socio,self.diligencias, self.fecha)


class Meta:
ordering = ['socio']

Thanks guys.

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: related_name in filter search

2008-10-13 Thread Karen Tracey
On Mon, Oct 13, 2008 at 4:22 AM, Alessandro Ronchi <
[EMAIL PROTECTED]> wrote:

> 2008/10/11 Karen Tracey <[EMAIL PROTECTED]>:
>
> > You've got a typo in there somewhere, because there is no 'notizie' in
> the
> > query you posted, you've got 'schede' like above.  So I'm not sure
> exactly
> > what you tried nor exactly what error you got.  Cut and paste of code and
> > error messages is best to avoid confusion.  Also, posting complete models
> > instead of just snippets (put them out on dpaste.com and point to them
> if
> > they are non-trivial and thus will display poorly in email) may be better
> in
> > this case.  From what you posted so far I don't see why what (I'm
> guessing)
> > your query was isn't working.
>
> This is my models.py:
> http://dpaste.com/84075/
>
> This is my urls.py:
> http://dpaste.com/84077/
> (che commented line is the one that gives the error)
> #
> ultima_edizione=Edizione.objects.distinct().filter(notizie__isnull=False).order_by('-id')
>
>
> This is the error i Get:
>
> http://dpaste.com/84076/
>
> Thanks in advance!
>

I can't recreate your error because any attempt to use the models.py you
point to produces an error on the declaration of the Edizione ForeignKey
field within model Notizia:

edizione = models.ForeignKey(Edizione, related_name="notizie",
default=ultima_edizione)
NameError: name 'ultima_edizione' is not defined

So I am not sure exactly how you are getting as far as you are with this
models.py.  (It's also missing any declaration of the model Download that is
referenced in the urls.py you point at...) But I think you have a
chicken-and-egg sort of problem since the line you are saying does not work
is:

ultima_edizione=Edizione.objects.distinct().filter(notizie__isnull=False).order_by('-id')

So loading the Notizia model requires resolving ultima_edizione, but
ultima_edizione requires the Notizia model to be fully initialized since it
is the Edizione ForeignKey within Notizia which causes the 'notizie'
attribue to be added to Edizione.  (Also, even if this worked,
ultima_edizone ends up being a QuerySet there, not an Edizione instance, so
it wouldn't work as a default value.)

Simply adding an import of the missing ultima_edizione to models.py produces
an import error that Notizia cannot be imported due to the circular
reference, in the backtrace you see:

from urls import ultima_edizione
...
from models import Notizia, Edizione
...
from urls import ultima_edizione
...
from models import Notizia, Edizione
ImportError: cannot import name Notizia

which is what I would expect given what you have.  So I'm not sure how you
are getting around the circular import but it seems to result in
ultima_edizione being processed using an incompletely loaded model set,
since Edizione does not have the attribute that will be created when the
Notzia model is loaded.

I think you need to take a step back and rethink that default= on the
edizione ForeignKey.  What are you really trying to accomplish?

Karen

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: related_name in filter search

2008-10-13 Thread Alessandro
2008/10/11 Karen Tracey <[EMAIL PROTECTED]>:

> You've got a typo in there somewhere, because there is no 'notizie' in the
> query you posted, you've got 'schede' like above.  So I'm not sure exactly
> what you tried nor exactly what error you got.  Cut and paste of code and
> error messages is best to avoid confusion.  Also, posting complete models
> instead of just snippets (put them out on dpaste.com and point to them if
> they are non-trivial and thus will display poorly in email) may be better in
> this case.  From what you posted so far I don't see why what (I'm guessing)
> your query was isn't working.
>


This is my models.py:
http://dpaste.com/84075/

This is my urls.py:
http://dpaste.com/84077/
(che commented line is the one that gives the error)
# 
ultima_edizione=Edizione.objects.distinct().filter(notizie__isnull=False).order_by('-id')


This is the error i Get:

http://dpaste.com/84076/

Thanks in advance!


-- 
Alessandro Ronchi
Skype: aronchi
http://www.alessandroronchi.net

SOASI Soc.Coop. - www.soasi.com
Sviluppo Software e Sistemi Open Source
Sede: Via Poggiali 2/bis, 47100 Forlì (FC)
Tel.: +39 0543 798985 - Fax: +39 0543 579928

Rispetta l'ambiente: se non ti è necessario, non stampare questa mail

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: related_name in filter search

2008-10-13 Thread Alessandro Ronchi
2008/10/11 Karen Tracey <[EMAIL PROTECTED]>:

> You've got a typo in there somewhere, because there is no 'notizie' in the
> query you posted, you've got 'schede' like above.  So I'm not sure exactly
> what you tried nor exactly what error you got.  Cut and paste of code and
> error messages is best to avoid confusion.  Also, posting complete models
> instead of just snippets (put them out on dpaste.com and point to them if
> they are non-trivial and thus will display poorly in email) may be better in
> this case.  From what you posted so far I don't see why what (I'm guessing)
> your query was isn't working.

This is my models.py:
http://dpaste.com/84075/

This is my urls.py:
http://dpaste.com/84077/
(che commented line is the one that gives the error)
# 
ultima_edizione=Edizione.objects.distinct().filter(notizie__isnull=False).order_by('-id')


This is the error i Get:

http://dpaste.com/84076/

Thanks in advance!

-- 
Alessandro Ronchi
Skype: aronchi
http://www.alessandroronchi.net

Rispetta l'ambiente: se non ti è necessario, non stampare questa mail

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: related_name in filter search

2008-10-11 Thread Karen Tracey
On Fri, Oct 10, 2008 at 3:19 PM, Alessandro <[EMAIL PROTECTED]>wrote:

> In a project I have
> class Scheda(models.Model):
>referente = models.ForeignKey(User,related_name="schede",
> editable=False)
>
> and I can use:
> User.objects.distinct().filter(schede__isnull=False):
>
> in another I have
> class Notizia(models.Model):
>edizione = models.ForeignKey(Edizione, related_name="notizie",
> default=ultima_edizione)
>
> and
> Edizione.objects.distinct().filter(schede__isnull=False).order_by('-id')[0]
>
> returns
>
> FieldError: Cannot resolve keyword 'notizie' into field. Choices are:
> id, nome, slug
>

You've got a typo in there somewhere, because there is no 'notizie' in the
query you posted, you've got 'schede' like above.  So I'm not sure exactly
what you tried nor exactly what error you got.  Cut and paste of code and
error messages is best to avoid confusion.  Also, posting complete models
instead of just snippets (put them out on dpaste.com and point to them if
they are non-trivial and thus will display poorly in email) may be better in
this case.  From what you posted so far I don't see why what (I'm guessing)
your query was isn't working.

Karen

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



related_name in filter search

2008-10-10 Thread Alessandro
In a project I have
class Scheda(models.Model):
referente = models.ForeignKey(User,related_name="schede", editable=False)

and I can use:
User.objects.distinct().filter(schede__isnull=False):

in another I have
class Notizia(models.Model):
edizione = models.ForeignKey(Edizione, related_name="notizie",
default=ultima_edizione)

and
Edizione.objects.distinct().filter(schede__isnull=False).order_by('-id')[0]

returns

FieldError: Cannot resolve keyword 'notizie' into field. Choices are:
id, nome, slug

so I must use:
for edizione in Edizione.objects.distinct().order_by('-id'):
if edizione.notizie.count() > 0:
ultima_edizione = edizione

and it works

do you know where is the problem?
-- 
Alessandro Ronchi
Skype: aronchi
http://www.alessandroronchi.net

SOASI Soc.Coop. - www.soasi.com
Sviluppo Software e Sistemi Open Source
Sede: Via Poggiali 2/bis, 47100 Forlì (FC)
Tel.: +39 0543 798985 - Fax: +39 0543 579928

Rispetta l'ambiente: se non ti è necessario, non stampare questa mail

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: how to access foreignkey field (related_name) in newforms-admin list view?

2008-07-18 Thread Andre Meyer
hi Rajesh

so, implemented it as you told and it works very well.

thanks for your patience and all the explanations.

cheers
André


On Thu, Jul 17, 2008 at 7:22 PM, Rajesh Dhawan <[EMAIL PROTECTED]>
wrote:

>
>
> > > > still, it's not exactly clear to me why the admin does not work the
> same
> > > as
> > > > other templates.
> >
> > > The Admin is not a template. So, I don't know what you mean by that.
> >
> > admin is not using templates? well, i did not check the implementation.
>
> Sorry, if I wasn't clear. The admin does use templates but it's much
> more than that (that's why I said that the Admin is not a template).
> Moreover, the Admin change-list and all its other templates have to be
> dynamic because they don't know beforehand what fields each model is
> going to have and which of those are going to be displayed via
> list_display.
>
> So, as I explained above, there's no way for the admin to guess what
> you want it to do with related many-valued fields like Post.comments
> in your case. So, it chokes when you try to do such a thing.
>
> >
> > The whole point is that in your own template, you decide whether you
> >
> > > want to display the count of comments or a list of comments or the
> > > names of the commenters, and so on. How would the Admin know what you
> > > want if you were allowed to put "comments" in the list_display? One
> > > user may want the count, another may want something else. That's why
> > > the Admin supports calling methods in your model class. And through
> > > such methods you are able to display your comments field exactly the
> > > way you want.
> >
> > agree, though it would make sense to me to return the RelatedManager
> > instance, just like in the templates.
>
> What would that give you? In the change list you would just see the
> class name of the RelatedManager. Is that what you mean?
>
> Remember that in your own templates, you don't just say:
>
> {{ post.comments }}
>
> Instead you either loop over comments or do a length filter on them,
> etc. In other words, you are actively making the decision on what you
> want to do with that related manager instance.
>
> Also, there's one other important difference: when you loop over
> post.comments in your template, you are causing a DB query that brings
> in the comments of that single  post instance. If an Admin were to do
> that, it would have to issue an extra query for each row it is going
> to display in the change-list screen.
>
> All this is documented in the second bullet here:
>
> http://www.djangoproject.com/documentation/model-api/#list-display
>
> -Rajesh
> >
>

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: how to access foreignkey field (related_name) in newforms-admin list view?

2008-07-17 Thread Rajesh Dhawan


> > > still, it's not exactly clear to me why the admin does not work the same
> > as
> > > other templates.
>
> > The Admin is not a template. So, I don't know what you mean by that.
>
> admin is not using templates? well, i did not check the implementation.

Sorry, if I wasn't clear. The admin does use templates but it's much
more than that (that's why I said that the Admin is not a template).
Moreover, the Admin change-list and all its other templates have to be
dynamic because they don't know beforehand what fields each model is
going to have and which of those are going to be displayed via
list_display.

So, as I explained above, there's no way for the admin to guess what
you want it to do with related many-valued fields like Post.comments
in your case. So, it chokes when you try to do such a thing.

>
> The whole point is that in your own template, you decide whether you
>
> > want to display the count of comments or a list of comments or the
> > names of the commenters, and so on. How would the Admin know what you
> > want if you were allowed to put "comments" in the list_display? One
> > user may want the count, another may want something else. That's why
> > the Admin supports calling methods in your model class. And through
> > such methods you are able to display your comments field exactly the
> > way you want.
>
> agree, though it would make sense to me to return the RelatedManager
> instance, just like in the templates.

What would that give you? In the change list you would just see the
class name of the RelatedManager. Is that what you mean?

Remember that in your own templates, you don't just say:

{{ post.comments }}

Instead you either loop over comments or do a length filter on them,
etc. In other words, you are actively making the decision on what you
want to do with that related manager instance.

Also, there's one other important difference: when you loop over
post.comments in your template, you are causing a DB query that brings
in the comments of that single  post instance. If an Admin were to do
that, it would have to issue an extra query for each row it is going
to display in the change-list screen.

All this is documented in the second bullet here:

http://www.djangoproject.com/documentation/model-api/#list-display

-Rajesh
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: how to access foreignkey field (related_name) in newforms-admin list view?

2008-07-17 Thread Andre Meyer
hi Rajesh

On Thu, Jul 17, 2008 at 6:55 PM, Rajesh Dhawan <[EMAIL PROTECTED]>
wrote:

>
> Hi,
>
> > still, it's not exactly clear to me why the admin does not work the same
> as
> > other templates.
>
> The Admin is not a template. So, I don't know what you mean by that.


admin is not using templates? well, i did not check the implementation.


The whole point is that in your own template, you decide whether you
> want to display the count of comments or a list of comments or the
> names of the commenters, and so on. How would the Admin know what you
> want if you were allowed to put "comments" in the list_display? One
> user may want the count, another may want something else. That's why
> the Admin supports calling methods in your model class. And through
> such methods you are able to display your comments field exactly the
> way you want.


agree, though it would make sense to me to return the RelatedManager
instance, just like in the templates.

anyway, problem solved

thanks a lot
André

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: how to access foreignkey field (related_name) in newforms-admin list view?

2008-07-17 Thread Rajesh Dhawan

Hi,

> still, it's not exactly clear to me why the admin does not work the same as
> other templates.

The Admin is not a template. So, I don't know what you mean by that.

>
> in my own template, it is no problem to refer to comments of a post using,
> e.g.
>
> {% for comment in post.comments.all %}
> [...]
> {% endfor %}
>
> or
>
> {{ post.comments.all|length }}
>
> looks inconsistent to me.

The whole point is that in your own template, you decide whether you
want to display the count of comments or a list of comments or the
names of the commenters, and so on. How would the Admin know what you
want if you were allowed to put "comments" in the list_display? One
user may want the count, another may want something else. That's why
the Admin supports calling methods in your model class. And through
such methods you are able to display your comments field exactly the
way you want.

-Rajesh D


--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: how to access foreignkey field (related_name) in newforms-admin list view?

2008-07-17 Thread Andre Meyer
hi Rajesh

thanks, that's a great link.

still, it's not exactly clear to me why the admin does not work the same as
other templates.

in my own template, it is no problem to refer to comments of a post using,
e.g.

{% for comment in post.comments.all %}
[...]
{% endfor %}

or

{{ post.comments.all|length }}

looks inconsistent to me.

thanks & cheers
André


On Thu, Jul 17, 2008 at 4:14 PM, Rajesh Dhawan <[EMAIL PROTECTED]>
wrote:

>
>
>
> On Jul 17, 8:32 am, "Andre Meyer" <[EMAIL PROTECTED]> wrote:
> > hi all
> >
> > imagine you have a first model class and a second model class with a
> > ForeignKey referring to the first one. for example, a Post model (taken
> from
> > the tutorial blog app) and a Comment model. of course, a post can have
> > multiple comments, so the Post model gets an attribute 'comments'
> (specified
> > using related_name).
> >
> > how can the comments be displayed in the list view of the posts using
> > newforms-admin? i would like to indicate whether there are comments and
> how
> > many, if any.
>
> Create a method in your Post class like this:
>
> def comment_stats(self):
>   return self.comments.count()
>
> Then add 'comment_stats' to the list_display of your Post's Admin
> options.
>
> >
> > but when adding the 'comments' attribute to the list_display of
> PostOptions,
> > syncdb throws an exception:
> >
> > *django.core.exceptions.ImproperlyConfigured:
> `PostOptions.list_display[13]`
> > refers to `comments` that is neither a field, method or property of model
> > `Post`.
> > *
> > which is not true! Post does get a 'comments' field by the definition of
> > Comment.
>
> From the Post's perspective comments is a multi-valued field. However,
> the Admin list_display of Post is intended to show one Post record per
> row. So displaying post.comments where comments can have a dozen rows
> per post doesn't make sense i.e. the Admin can't guess that you want
> to show just the presence of comments as a boolean flag or that you
> want to show the count of comments. The above technique of using a
> custom method is how you can accomplish what you want here.
>
> See:
>
> http://code.djangoproject.com/wiki/NewformsHOWTO#Q:HowdoIaddanextracolumntothechangelistview
>
> -Rajesh D
> >
>

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: how to access foreignkey field (related_name) in newforms-admin list view?

2008-07-17 Thread Rajesh Dhawan



On Jul 17, 8:32 am, "Andre Meyer" <[EMAIL PROTECTED]> wrote:
> hi all
>
> imagine you have a first model class and a second model class with a
> ForeignKey referring to the first one. for example, a Post model (taken from
> the tutorial blog app) and a Comment model. of course, a post can have
> multiple comments, so the Post model gets an attribute 'comments' (specified
> using related_name).
>
> how can the comments be displayed in the list view of the posts using
> newforms-admin? i would like to indicate whether there are comments and how
> many, if any.

Create a method in your Post class like this:

def comment_stats(self):
   return self.comments.count()

Then add 'comment_stats' to the list_display of your Post's Admin
options.

>
> but when adding the 'comments' attribute to the list_display of PostOptions,
> syncdb throws an exception:
>
> *django.core.exceptions.ImproperlyConfigured: `PostOptions.list_display[13]`
> refers to `comments` that is neither a field, method or property of model
> `Post`.
> *
> which is not true! Post does get a 'comments' field by the definition of
> Comment.

>From the Post's perspective comments is a multi-valued field. However,
the Admin list_display of Post is intended to show one Post record per
row. So displaying post.comments where comments can have a dozen rows
per post doesn't make sense i.e. the Admin can't guess that you want
to show just the presence of comments as a boolean flag or that you
want to show the count of comments. The above technique of using a
custom method is how you can accomplish what you want here.

See:
http://code.djangoproject.com/wiki/NewformsHOWTO#Q:HowdoIaddanextracolumntothechangelistview

-Rajesh D
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



how to access foreignkey field (related_name) in newforms-admin list view?

2008-07-17 Thread Andre Meyer
hi all

imagine you have a first model class and a second model class with a
ForeignKey referring to the first one. for example, a Post model (taken from
the tutorial blog app) and a Comment model. of course, a post can have
multiple comments, so the Post model gets an attribute 'comments' (specified
using related_name).

how can the comments be displayed in the list view of the posts using
newforms-admin? i would like to indicate whether there are comments and how
many, if any.

but when adding the 'comments' attribute to the list_display of PostOptions,
syncdb throws an exception:

*django.core.exceptions.ImproperlyConfigured: `PostOptions.list_display[13]`
refers to `comments` that is neither a field, method or property of model
`Post`.
*
which is not true! Post does get a 'comments' field by the definition of
Comment.

inlined comments do appear in the detail view, though.

what's wrong?

thanks for your help
André

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: bypassing reverse relation (related_name)

2007-10-17 Thread RajeshD

>
> Is there a way to express that I don't need the reverse relation?

No. Even if you don't need them, Django will want to dynamically endow
your Location objects with them. And, as you know, it can't do it if
two reverse relations have the same name.


--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



bypassing reverse relation (related_name)

2007-10-17 Thread Joe Holloway

I'm finding that I have quite a few many-to-one relations that don't
really need the reverse relation to be expressed in the object model.
For example,

class Route(models.Model):
start = models.ForeignKey (Location)
destination = models.ForeignKey (Location)

The default related_name clashes here, so I must specify my own:

class Route(models.Model):
start = models.ForeignKey (Location, related_name='starting_points')
finish = models.ForeignKey (Location,

related_name='finishing_points')

In these cases, I always tend to come up with hokey names like above
since the reverse relation doesn't represent anything in the real
domain.  Since I know I'll never need to walk the relation backwards,
so it seems like a decision I could avoid making altogether.

Is there a way to express that I don't need the reverse relation?

Thanks,
Joe

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: related_name

2007-08-06 Thread Lic. José M. Rodriguez Bacallao
right now, I find out how but, anyway, I'll give U an example:

every ForeigmKey have a related_name parameter in its constructor, the
problem is how to change that value once we construct the ForeignKey object.
I did so changing the value of the: foreignkey_object.rel.related_name at
runtime.

On 8/4/07, Amirouche <[EMAIL PROTECTED]> wrote:
>
>
>
>
> On Aug 1, 10:07 pm, "Lic. José M. Rodriguez Bacallao"
> <[EMAIL PROTECTED]> wrote:
> > how can I change the "related_name" value in a ForeignKey field
> dynamically
> > at model creation time?
> >
>
> What do you really mean I don't understand, give an example
>
>
> >
>


-- 
Lic. José M. Rodriguez Bacallao
Cupet
-
Todos somos muy ignorantes, lo que ocurre es que no todos ignoramos lo
mismo.

Recuerda: El arca de Noe fue construida por aficionados, el titanic por
profesionales
-

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: related_name

2007-08-04 Thread Amirouche



On Aug 1, 10:07 pm, "Lic. José M. Rodriguez Bacallao"
<[EMAIL PROTECTED]> wrote:
> how can I change the "related_name" value in a ForeignKey field dynamically
> at model creation time?
>

What do you really mean I don't understand, give an example


--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



related_name

2007-08-01 Thread Lic. José M. Rodriguez Bacallao
how can I change the "related_name" value in a ForeignKey field dynamically
at model creation time?

-- 
Lic. José M. Rodriguez Bacallao
Cupet
-
Todos somos muy ignorantes, lo que ocurre es que no todos ignoramos lo
mismo.

Recuerda: El arca de Noe fue construida por aficionados, el titanic por
profesionales
-

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



related_name

2007-08-01 Thread Lic. José M. Rodriguez Bacallao
how can I change the "related_name" value in a ForeignKey field dynamically
at model creation time?

-- 
Lic. José M. Rodriguez Bacallao
Cupet
-
Todos somos muy ignorantes, lo que ocurre es que no todos ignoramos lo
mismo.

Recuerda: El arca de Noe fue construida por aficionados, el titanic por
profesionales
-

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Accessor for field 'somefield' clashes with related field ... Add a related_name argument to the definition for 'somefield'

2006-12-24 Thread Malcolm Tredinnick


On Wed, 2006-12-20 at 06:00 +, [EMAIL PROTECTED] wrote:

Hi... I was wondering why when you have something like this:
class Loan(models.Model):
loan_id = models.AutoField(primary_key=True)
originator =models.ForeignKey(UserInfo,null=True)
obligor = models.ForeignKey(UserInfo,null=True)

Why it gives you errors..until you change it to this:
class Loan(models.Model):
loan_id = models.AutoField(primary_key=True)
originator =models.ForeignKey(UserInfo,
related_name="originator",null=True)
obligor = models.ForeignKey(UserInfo,
related_name="obligor",null=True)



Why doesn't django just just look at the name you have specified before
the equal sign..rather than making you put the same thing in a
related_name field?


Two reasons, a technical Python one and a simpler Django one:

(1) At the time the ForeignKey class is created, it has no idea what it
is going to be assigned to (the name of the attribute). This is the
Python reason.

(2) The Django reason is because the default related name comes from the
model name. So if you are creating multiple relations to the same model
(UserInfo in this case) in one model, you must specify the related_name
in order to resolve the ambiguities (you only need to set the related
name on one of those fields, I suspect). Django never tries to guess
what you want to do when the defaults don't work. You choose to use the
field names, however, they are singular nouns and the reverse relation
is usually a set (a collection of multiple objects), so the singular
form is not necessarily the natural word to use here.

Hope that clarifies things a little bit.

Regards,
Malcolm


--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups "Django 
users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Accessor for field 'somefield' clashes with related field ... Add a related_name argument to the definition for 'somefield'

2006-12-23 Thread [EMAIL PROTECTED]


Hi... I was wondering why when you have something like this:
class Loan(models.Model):
   loan_id = models.AutoField(primary_key=True)
   originator =models.ForeignKey(UserInfo,null=True)
   obligor = models.ForeignKey(UserInfo,null=True)

Why it gives you errors..until you change it to this:
class Loan(models.Model):
   loan_id = models.AutoField(primary_key=True)
   originator =models.ForeignKey(UserInfo,
related_name="originator",null=True)
   obligor = models.ForeignKey(UserInfo,
related_name="obligor",null=True)



Why doesn't django just just look at the name you have specified before
the equal sign..rather than making you put the same thing in a
related_name field?


--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups "Django 
users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Difficulty accessing via related_name

2006-09-09 Thread Russell Keith-Magee

On 9/10/06, Hawkeye <[EMAIL PROTECTED]> wrote:
>
> Ah ha!  Thank you... I now see the error of my ways!
>
> Since I'm using unique=True, is there any way to avoid the [0] mumbo
> jumbo? (I don't see any but I figure it won't hurt to ask).

No. A foreign key is a many-to-one relation. In your case, every Foo
has a single User, but any given user could be linked to several
Foo's. Therefore, the reverse relation (user.foo) is a list of
objects.

Unique is a database level constraint that doesn't affect the query API.

If you are actually looking for a 1-1 relation, there is a
models.OneToOneField available, and doesn't require the '[0] mumbo
jumbo'. It works, but be warned: it may be subject to change in the
near future. One of the developers (Malcolm Tredinnick) is working on
some changes to model inheritance that will affect this field type.

Yours,
Russ Magee %-)

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users
-~--~~~~--~~--~--~---



Re: Difficulty accessing via related_name

2006-09-09 Thread Hawkeye

Ah ha!  Thank you... I now see the error of my ways!

Since I'm using unique=True, is there any way to avoid the [0] mumbo
jumbo? (I don't see any but I figure it won't hurt to ask).

Thanks,
  --Ben


--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users
-~--~~~~--~~--~--~---



Re: Difficulty accessing via related_name

2006-09-09 Thread Russell Keith-Magee

On 9/10/06, Hawkeye <[EMAIL PROTECTED]> wrote:

> print "User's Foo: %s" % request.user.foo
> 
> ==

request.user.foo is a manager, same as User.objects. The manager
itself isn't a list of objects; you need to use one of the manager
methods (like all(), filter() etc) to get the actual objects in the
relation. So, something like

print "User's foo: %s" % request.user.foo.all()

should print what you are after.

> When I try to traverse the reference, I can't access any of the
> functions or attributes
> ==
> request.user.foo.some_function()
> AttributeError at /foos/1/
> 'RelatedManager' object has no attribute 'some_function'
> ==

Again; request.user.foo isn't an object at this point. You need to
poke the related manager to get an object instance before you can
invoke a method on it.

# Get the first related object and call some_function on it.
request.user.foo.all()[0].some_function()

# Get the foo object with id=1, and call some_function on it
request.user.foo.get(id=1).some_function()

# Call some function on all related foo objects.
[f.some_function() for f in request.user.foo.all()]

Hope this helps.

Yours,
Russ Magee %-)

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users
-~--~~~~--~~--~--~---



Difficulty accessing via related_name

2006-09-09 Thread Hawkeye

Hi folks,

I'm trying to develop an application that 'extends' the User object.
I'm using the 'related_name' argument for ForeignKey to access the
related objects through request.user

I have a class, similar to this
==
class Foo(models.Model):
user = models.ForeignKey(User, edit_inline=models.TABULAR unique-True,
related_name='foo')

def __str__(self):
return "Foo ID#%s" % self.id

def some_function(self):
return "Result"
==

If I try to display the relationship, I'd expect to get 'Foo ID#1', but
I get this...
==
print "User's Foo: %s" % request.user.foo

==

When I try to traverse the reference, I can't access any of the
functions or attributes
==
request.user.foo.some_function()
AttributeError at /foos/1/
'RelatedManager' object has no attribute 'some_function'
==

Am I doing something wrong? Making an incorrect assumption about the
functionality of Django?

Any insight would be appreciated! Thanks!
  --Ben


--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users
-~--~~~~--~~--~--~---



Re: ManyToMany with related_name?

2006-04-12 Thread Russell Keith-Magee
On 4/13/06, Dave St.Germain <[EMAIL PROTECTED]> wrote:
I'm trying to create a model that relates back to itself with a ManyToManyField.  Here's my model:I'd like to use a simple ManyToMany, but the objects don't have a distinction between "inserted into" and "insert of".  
Does that make sense?Yup. The problem here is that Django assumes that if you have a ManyToMany field on self, then the relationship is symmetrical: for example:class Person:
   friend = ManyToManyField('self')If I am your friend, then presumably you are my friend. To avoid confusion, the reverse representation of the relationship (person_set, or whatever related_name specifies) is not added to instances of Person.
Obviously, there are some use cases (such as yours) where this is not the case - to handle these, you need to set symmetrical=False:
insert_into = models.ManyToManyField('self',
  null=True,
  blank=True,
  related_name='insert'
  symmetrical=False)

This will add the related_name member on the related object, and will be a distinct set; adding to PressRun.insert_into is not the same as adding to PressRun.insertHope this helps,Russ Magee %-)

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups "Django users" group.  To post to this group, send email to django-users@googlegroups.com  To unsubscribe from this group, send email to [EMAIL PROTECTED]  For more options, visit this group at http://groups.google.com/group/django-users  -~--~~~~--~~--~--~---


ManyToMany with related_name?

2006-04-12 Thread Dave St.Germain
I'm trying to create a model that relates back to itself with a ManyToManyField.  Here's my model:class PressRun(models.Model):    starttime = models.DateTimeField(db_index=True)    endtime = models.DateTimeField
(validator_list=[endAfterStartValidator])    name = models.CharField(maxlength=100,blank=True)    recurringitem = models.ForeignKey(RecurringPressRun,blank=True,null=True)    edition = models.IntegerField(choices=EDITION_CHOICES,blank=True,null=True)
    press_id = models.IntegerField(choices=PRESS_CHOICES,blank=True,default=1)    insert_into = models.ManyToManyField('self',  null=True,  blank=True,  related_name='insert')
The problem is that the model doesn't seem to use the related_name option.  PressRun objects have an insert_into property, but no insert property.  I'm actually trying to say that the result of a PressRun can be "inserted" into another PressRun, but I don't want to make a separate object (like PressRunInsert or something).  I'd like to use a simple ManyToMany, but the objects don't have a distinction between "inserted into" and "insert of".  
Does that make sense?Dave

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups "Django users" group.  To post to this group, send email to django-users@googlegroups.com  To unsubscribe from this group, send email to [EMAIL PROTECTED]  For more options, visit this group at http://groups.google.com/group/django-users  -~--~~~~--~~--~--~---