Django manytomany object_set query by field - django

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_')

Related

Object has no attribute on a Textfield in Django

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.

How to show choices of field in another table(model) value?

How to show choices of field in another table value?
I want to Nutritionalkey show on the NutritionalValues choice field
class Nutritionalkey(models.Model):
key = models.CharField(max_length=1000)
def __unicode__(self):
return self.key
class NutritionalValues(models.Model):
key = models.CharField(max_length=100, choices=Nutritionalkey.key)
value=models.FloatField(null=True, blank=True, default=None)
product=models.ForeignKey(Product,null=True, blank=True)
class Meta:
verbose_name_plural = 'NutritionalValues'
verbose_name = 'NutritionalValue'
def __unicode__(self):
return '%s %s' % (self.product.productName,self.key)
As django doc says:
But if you find yourself hacking choices to be dynamic, you’re
probably better off using a proper database table with a ForeignKey.
You should then have:
class NutritionalValues(models.Model):
key = models.ForeignKey(Nutritionalkey)
...

ForeignKey(unique=True) is usually better served by a OneToOneField

class Categories(models.Model):
id = models.ForeignKey('auth.User',primary_key=True)
name = models.CharField(max_length=100)
description = models.CharField(max_length=300)
def __str__(self):
return Categories.name
class Meta:
order_with_respect_to = 'id'
class Specializations(models.Model):
id = models.ForeignKey('auth.User',primary_key=True)
name = models.CharField(max_length=100)
description = models.CharField(max_length=300)
categories = models.ForeignKey(Categories, on_delete=models.CASCADE)
def __str__(self):
return Specializations.name
courses.Categories.id: (fields.W342) Setting unique=True on a ForeignKey has the same effect as using a OneTo
OneField.
HINT: ForeignKey(unique=True) is usually better served by a OneToOneField.
courses.Courses.id: (fields.W342) Setting unique=True on a ForeignKey has the same effect as using a OneToOne
Field.
HINT: ForeignKey(unique=True) is usually better served by a OneToOneField.
courses.Specializations.id: (fields.W342) Setting unique=True on a ForeignKey has the same effect as using a
OneToOneField.
This warning or error raises although the relation is one to many !! not one to one
The way you designed your models it is essentially a OneToOne relationship, because you set the ForeignKey to be the primary_key (this automatically aplies unique=True).
Do you really want to the user to be the primary_key of Categories or Specializations?
I think you want something like this:
class Categories(models.Model):
user = models.ForeignKey('auth.User')
name = models.CharField(max_length=100)
description = models.CharField(max_length=300)
def __str__(self):
return self.name
class Specializations(models.Model):
user = models.ForeignKey('auth.User')
name = models.CharField(max_length=100)
description = models.CharField(max_length=300)
categories = models.ForeignKey(Categories, on_delete=models.CASCADE)
def __str__(self):
return self.name
With this a User can have many Categories and Specializations
I also changed the __str__ method to self.name

Unable to save m2m relation modelform

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.

ManyToMany model error

I have a Cruise offer class related to a model called SpecialInterest. I now realize that I have the same exact thing going on in my LandOffer model (elsewhere). So I want to get rid of the cruise.SpecialInterest and replace it with the land.SpecialInterest.
This is my error:
Error: One or more models did not validate:
cruise.cruiseoffer: 'special_interest' has an m2m relation with model land.models.SpecialInterest, which has either not been installed or is abstract.
I dropped the CruiseOffer table, but when I syncdb I fail.
Help?
class CruiseOffer(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=300) # Field name made lowercase.
name_enca = models.CharField(max_length=300, blank=True) # Field name made lowercase.
name_frca = models.CharField(max_length=300, blank=True) # Field name made lowercase.
supplier = models.ForeignKey('CruiseSupplier')
#special_interest = models.ManyToManyField('SpecialInterest')
special_interest = models.ManyToManyField('land.models.SpecialInterest')
def __unicode__(self):
return "%6d %s" % (self.id, self.name,)
Right syntax is:
from land.models import SpecialInterest
...
class Crui...
...
special_interest = models.ManyToManyField(SpecialInterest)