I am getting a
'Sponsor' object has no attribute 'adtag'
error, when I try to pull data from a foreign key field in Django.
When I try to pull CharField data from the same model, that works perfectly fine.
Here are my models:
class Sponsor(models.Model):
name = models.CharField("Name of Sponsor", max_length=120, blank=False)
...
adtag = models.TextField(name="Ad Tag")
def __str__(self):
return self.name
and
class Merchant(models.Model):
name = models.CharField("Name des Betriebs", max_length=120, blank=False)
sponsor = models.ForeignKey(Sponsor, on_delete=models.PROTECT)
def __str__(self):
return self.name
I am calling this by doing this:
merchant = Merchant.objects.filter(id=merchant)
and
print(merchant.sponsor.adtag)
And of course the data is filled in in the database + foreign key is associated.
Thanks for any recommendation.
Turns out that the name= option here is defining the field name in the database. So it was looking for "Ad Tag" als a column name, not adtag.
Related
i encountered the following problem when i try to migrate list of models one of which contains a ManyToMany field.
class Item(models.Model):
File "C:\Users\helin\Downloads\Django\E-commerce\Farmers\Farmersapp\models.py", line 60, in Item
sluger = farmer.First_Name
AttributeError: 'ManyToManyField' object has no attribute 'First_Name'
Below are the models i created.any help is appreciated.Thank you
class Farmer(models.Model):
id = models.AutoField(default=1,primary_key=True)
First_Name = models.CharField(max_length=15)
Last_Name = models.CharField(max_length=15)
def __str__(self):
return self.First_Name+" "+self.Last_Name
def get_farmer(self):
return self.farmer.First_Name+" " +self.farmer.Last_Name
class Item(models.Model):
id = models.AutoField(default=1,primary_key=True)
category = models.CharField(choices=CATEGORY_CHOICES, max_length=6)
price = models.FloatField()
description = models.TextField(blank=True)
image = models.ImageField()
farmer = models.ManyToManyField(Farmer, through='ItemAmount',related_name='item')
sluger = farmer.First_Name
slug = models.SlugField(default=sluger)
def __str__(self):
return self.category
class ItemAmount(models.Model):
farmer = models.ForeignKey(Farmer, on_delete=models.CASCADE)
item = models.ForeignKey(Item, on_delete=models.CASCADE)
quantity = models.IntegerField(default=1)
First, would suggest to take a look at Python style guide, like lowercase attribute names, etc.
Django auto-creates id primary-key field on every model, unless other field is set as primary-key. So, this part can be safely avoided.
get_farmer method - how is it different from str? Also, these are model instance methods ((self)), so there is no self.farmer field on Farmer object - this will fail.
class Farmer(models.Model):
# id AutoFied is created by default by django, so no need to specify
# id = models.AutoField(default=1,primary_key=True)
first_name = models.CharField(max_length=15)
last_name = models.CharField(max_length=15)
def __str__(self):
return self.first_name + " " + self.last_name
farmer = models.ManyToManyField() - as it is ManyToMany, this means many farmers, so it is better to name field farmers, also same applies to reverse relation - Farmer might have multiple items - related_name=items.
sluger - is it a field? Also, it might have many farmers, so which one to pick?
slug - referencing self fields in default is not good idea, better set default in forms.
You can make slug CharField and set its value in save() method for example.
class Item(models.Model):
# id AutoFied is created by default by django, so no need to specify
# id = models.AutoField(default=1,primary_key=True)
category = models.CharField(choices=CATEGORY_CHOICES, max_length=6)
price = models.FloatField()
description = models.TextField(blank=True)
image = models.ImageField()
farmers = models.ManyToManyField(
Farmer,
through='ItemAmount',related_name='items'
)
slug = models.SlugField()
def __str__(self):
return self.category
You can start with minimum working models and add new fields / methods one by one - it would be easier to debug and you will have base working app.
I'm struck on saving m2m relation.
models.py
class BasicTag(models.Model):
name = models.CharField(max_length=150, verbose_name="Tag Name")
image_class = models.CharField(max_length=30, blank=True)
color = models.CharField(max_length=10, blank=True)
def __unicode__(self):
return self.name
class ExtendedTag(models.Model):
parent = models.ManyToManyField(BasicTag, blank=True,
related_name="parent")
category = models.ManyToManyField(BasicTag, blank=True,
related_name="category")
def __unicode__(self):
return self._id
class CombineTag(BasicTag, ExtendedTag):
"""
"""
forms.py
class CombineTagForm(forms.ModelForm):
class Meta:
model = CombineTag
Now when I initialize form as
>form = CombineTagForm({"name":"shyam"})#this don't have any parent i.e. root tag
>form.is_valid()
True
>instance = form.save(commit = False)
>instance.save()
>form.save() #return errors
#error
ProgrammingError: column tag_extendedtag_parent.basictag_id does not exist
LINE 1: DELETE FROM "tag_extendedtag_parent" WHERE "tag_extendedtag_...
>form.save_m2m() #return errors ... struck here
So How should I need to save m2m field modelform. I had follow official doc which say that
If your model has a many-to-many relation and you specify commit=False when you save a form, Django cannot immediately save the form data for the many-to-many relation. This is because it isn’t possible to save many-to-many data for an instance until the instance exists in the database.
But I couldn't able to figure out what I am missing here.
I am working on my model classes, trying to get a class field from other class, but I am stuck on this.
Here are the classes:
class Cliente(models.Model):
nome = models.CharField(max_length=100, blank=True)
endereco = models.CharField(max_length=100, blank=True)
telefone = models.CharField(unique=True, max_length=10)
data = models.DateField()
def __unicode__(self):
return self.nome
I would like to get the "nome" field from the next class:
class Pedido(models.Model):
idcliente = models.ForeignKey(Cliente, db_column='idCliente')
def __unicode__(self):
return Cliente.objects.get(id=idcliente).nome, Pedido.id
This last method unicode doesn't get the nome from the Client object.
Also, I would like to get the id(primary key), that is not declared in the model, but the field is actually already created in the table. But I don't know how to get both fields.
Anyone please would help me get this thing to work?
Thanks a lot!!
You just have to follow the foreign key field like this:
class Pedido(models.Model):
idcliente = models.ForeignKey(Cliente, db_column='idCliente')
def __unicode__(self):
return self.idcliente.nome, self.id
The Django ORM will automatically perform a database lookup if required to required to load the appropriate Cliente row.
This will get the nome and the id.
What is the correct way of getting the 'contact' count from within my 'Group'?
I was thinking of just creating a new method within 'group' and filter(), but this means hitting the db again which seems bad, right?
class GroupManager(models.Manager):
def for_user(self, user):
return self.get_query_set().filter(user=user,)
class Group(models.Model):
name = models.CharField(max_length=60)
modified = models.DateTimeField(null=True, auto_now=True,)
#FK
user = models.ForeignKey(User, related_name="user")
objects = GroupManager()
def get_absolute_url(self):
return reverse('contacts.views.group', args=[str(self.id)])
class Contact(models.Model):
first_name = models.CharField(max_length=60)
last_name = models.CharField(max_length=60)
#FK
group = models.ForeignKey(Group)
group_object.contact_set.count() should do it. Django creates the relation by adding _set to the end of the foreign key's model name.
Have a look at the docs on related objects for more info.
I have ManyToMany field in model and i want to query it from another model which has _set field by default:
class Airport(models.Model):
name = models.CharField(max_length=1024, blank=True, null=True)
def __unicode__(self):
return unicode(self.name)
class Agent(models.Model):
name = models.CharField(max_length=1024, blank=True, null=True)
airports = models.ManyToManyField(Airport)
def __unicode__(self):
return unicode(self.name)
So query like:
a=Agents.objects.filter(airports_name_contains='asd')
works fine. But:
b=Airport.objects.filter(agent_set__name__contains='agent_')
gives
Cannot resolve keyword 'agent_set_name' into field
I want to query exactly Airport model. Any suggestions?
oops, my bad. I found solution. Django representaion of manytomany field shows "agent_set" in the lookup, but the field itself is "agent":
agents=Airport.objects.filter(agent_name_contains='agent_')