On Friday, 14 October 2011 12:44:45 UTC+1, Guy Nesher wrote:
>
>
> Hi, 
>
> I'm trying to populate a table with 2 foreign keys using a csv file 
> and keep getting the following error : 
> Cannot assign "238": "PrizetoRestaurant.RestauranttId" must be a 
> "Restaurant" instance. 
>
> I tried to manually define the primary keys in those tables, and I'm 
> making sure I int() the data from the csv, but still now luck. 
> I've also looked in the db and a restaurant with id 238 does exist in 
> the Restaurant table. 
>
> I'm attaching the relevant code bellow. 
>
> Thanks! 
>
> I have the following model: 
>
> class Restaurant(models.Model): 
> Id = models.IntegerField(unique=True, primary_key=True) 
> Name = models.CharField(max_length=128) 
> Address = models.CharField(max_length=128) 
> Zip = models.CharField(max_length=128) 
> City = models.CharField(max_length=128) 
> Phone = models.CharField(max_length=128) 
> Latitude = models.DecimalField(max_digits=11, decimal_places=9) 
> Longitude = models.DecimalField(max_digits=11, decimal_places=9) 
>
> class Prize(models.Model): 
> Id = models.IntegerField(unique=True, primary_key=True) 
> Name = models.CharField(max_length=128) 
> GroupId = models.ForeignKey('PrizeGroup', to_field='Id') 
>
> class PrizetoRestaurant(models.Model): 
> RestaurantId = models.ForeignKey('Restaurant', to_field='Id') 
> PrizeId = models.ForeignKey('Prize', to_field='Id') 
> Date = models.DateField() 
> Quantity = models.IntegerField() 
>
>
> and the code is : 
>
>
> import csv 
> reader = csv.reader(open("/Users/guy.nesher/Work/tmsw/swiss/src/ 
> monopoly/static/csv/dailydatatest.csv", "rU"), dialect='excel') 
> for row in reader: 
>   
> PrizetoRestaurant.objects.get_or_create(RestaurantId=int(row[0]), 
> PrizeId=prizedict[2], Date = row[10], Quantity = row[2]) 
>


The error is quite clear: you're getting an integer from the CSV, but 
Django's ForeignKey expects an actual instance of the related table. If 
you'd called your field something sensible like "restaurant" this would be 
more obvious.

You can actually assign the ID directly by postfixing _id to the field name 
- so in your case, it would be RestaurantId_id

Please, also read PEP8 and don't give your fields InitialCaps names - they 
should be lower_case_with_underscore.
--
DR. 

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/jrq9Q_VcyqQJ.
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.

Reply via email to