composite key not displaying orrecyl on django admin - python

I have an intermediary model betwen "estados" e "listaflor", the flora2estado uses a composite key- and a primary key to trick django not to throw errors at me-.
When i click in one object at django admin i get this error:
MultipleObjectsReturned at /admin/accounts/flora2estado/99/change/
get() returned more than one Flora2Estado -- it returned 5!
my models.py
class Estados(models.Model):
estado_id = models.AutoField(primary_key=True)
estado_nome = models.CharField(max_length=100, blank=True, null=True)
class Meta:
managed = False
db_table = 'estados'
class Familia(models.Model):
familia_id = models.AutoField(primary_key=True)
familia_nome = models.CharField(max_length=50, blank=True, null=True)
class Meta:
managed = False
db_table = 'familia'
class Flora2Estado(models.Model):
estado = models.OneToOneField(Estados, models.DO_NOTHING, )
especie_id = models.IntegerField()
flora2estado_id = models.AutoField( primary_key=True)
class Meta:
managed = False
db_table = 'flora2estado'
unique_together = (('estado', 'especie_id'),)
admin.py
admin.site.register(Flora2Estado)

Related

Show secondary foreign key values in the inline django admin

models.py
class FarmerAdvisory(BaseModel):
id = models.AutoField(db_column='id', primary_key=True)
title = models.CharField(db_column='title', max_length=200, null=True, blank=True)
description = models.CharField(db_column='description', max_length=750, null=True, blank=True)
farmer_id = models.ForeignKey(Farmer, on_delete=models.CASCADE, null=True, db_column='farmer_id')
class Meta:
verbose_name = 'Farmer Advisory'
verbose_name_plural = 'Farmer Advisories'
managed = True
db_table = 'farmer_advisory'
class ReplyFarmerAdvisory(BaseModel):
reply = models.CharField(db_column='reply', max_length=750, null=True, blank=True)
label = models.CharField(db_column='label', max_length=100, null=True, blank=True)
farmer_advisory_id = models.ForeignKey(FarmerAdvisory, on_delete=models.CASCADE, db_column='farmer_advisory_id')
objects = models.Manager()
class Meta:
verbose_name = 'Reply Farmer Advisory'
verbose_name_plural = 'Reply Farmer Advisories'
managed = True
db_table = 'reply_farmer_advisory'
class AdvisoryMedia(models.Model):
id = models.AutoField(db_column='id', primary_key=True)
farmer_advisory_id = models.ForeignKey(FarmerAdvisory, on_delete=models.CASCADE,
db_column='farmer_advisory_id',
null=True, blank=True)
reply_farmer_advisory_id = models.ForeignKey(ReplyFarmerAdvisory, on_delete=models.CASCADE,
db_column='reply_farmer_advisory_id', null=True, blank=True)
farmer_media_file = models.CharField(db_column='farmer_media_file', max_length=50, null=True, blank=True)
is_active = models.BooleanField(db_column='is_active', null=False, default=True)
reply_media_file = models.FileField(upload_to=content_file_name, null=True, blank=True,
db_column='reply_media_file')
class Meta:
verbose_name = 'Advisory Media'
verbose_name_plural = 'Advisories Media'
managed = True
db_table = 'advisory_media'
admin.py
class AdvisoryMediaInline(NestedStackedInline):
model = AdvisoryMedia
extra = 0
class ReplyFarmerAdvisoryInline(NestedStackedInline):
model = ReplyFarmerAdvisory
extra = 1
inlines = [AdvisoryMediaInline]
class FarmerAdvisoryAdmin(NestedModelAdmin):
inlines = [ReplyFarmerAdvisoryInline]
I want to show the fields with respect to the farmer advisory. But when i am adding fk_name = 'farmer_advisory_id' inside AdvisoryMediaInline, i am getting error stating
ValueError: fk_name 'farmer_advisory_id' is not a ForeignKey to
'farmer.ReplyFarmerAdvisory'.
But i want to show the farmer advisory related fields which is not coming by itself.
I think what is happening is the model is looking for values with respect to the to foreign key reply advisory media instead of farmer advisory media.
Please let me know if my question is understandable, if yes please guide me through it.

Django many-to-one relation with 3 tables

I dont want any foreign keys directly in my users table, and by default, when I add a foreing key field in my custom User model, Django generate 2 tabels like this:
When I add a many-to-many field in my Company model I get the 3 desired tables but it's made possible for the same user be in two different companys.
class Company(models.Model):
class Meta:
verbose_name = 'Company'
verbose_name_plural = 'Companys'
ordering = ['name']
db_table = 'companys'
id = models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, unique=True, verbose_name='ID Empresa')
name = models.CharField(max_length=100, verbose_name='Nome')
users = models.ManyToManyField(User, related_name='company', verbose_name='Users')
def __str__(self):
return self.name
I want Django to generate an additional table with only the Foreing Keys of the two models but keep the behevior of a many-to-one relationship between the two. like this:
you can make your third table by using a separate model
class Company(models.Model):
class Meta:
verbose_name = 'Company'
verbose_name_plural = 'Companys'
ordering = ['name']
db_table = 'companys'
id = models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, unique=True, verbose_name='ID Empresa')
name = models.CharField(max_length=100, verbose_name='Nome')
def __str__(self):
return self.name
class UserCompanyRelationModel(models.Model):
class Meta:
db_table = 'usr_comp'
user = models.OneToOneField(User, on_delete=models.CASCADE)
company = models.ForeignKey(Company, on_delete=models.CASCADE)

How to display a foreign key value instead of the id?

I have the following models :
class FlightSchedule(models.Model):
tail_number = models.ForeignKey(TailNumber, null=False)
flight_number = models.CharField(max_length=30, null=False)
flight_group_code = models.ForeignKey(FlightGroup, null=False)
origin_port_code = models.ForeignKey(Port, null=False, related_name="Origin")
destination_port_code = models.ForeignKey(Port, null=False, related_name="Destination")
flight_departure_time = models.TimeField()
start_date = models.DateField()
end_date = models.DateField()
def __unicode__(self):
return u'%s' % self.flight_number
class Meta:
verbose_name_plural = "Flight Schedule"
class FlightScheduleDetail(models.Model):
flight_date = models.CharField(max_length=30, null=False)
flight_number = models.ForeignKey(FlightSchedule, null=False, related_name="flight_number_schedule")
route_id = models.CharField(max_length=30, null=False, unique=True)
flight_status = models.ForeignKey(Status, null=True, default=1)
def __unicode__(self):
return u'%s' % self.route_id
class Meta:
verbose_name_plural = "Flight Schedule Details"
and the serializer is as below :
class FlightScheduleDetailSerializer(serializers.ModelSerializer):
class Meta:
model = FlightScheduleDetail
fields = '__all__'
class FlightScheduleSerializer(serializers.ModelSerializer):
flight_number_schedule = FlightScheduleDetailSerializer(many=True)
class Meta:
model = FlightSchedule
fields = ['tail_number', 'flight_number', 'origin_port_code', 'destination_port_code', 'flight_departure_time',
'flight_number_schedule']
Here tail_number , flight_number is a foreign key. When I create an API, I get the response as the id of the fields. How can I display the name in the json?
My views.py is as below :
#api_view(['GET'])
def flight_schedule(request):
schedule = FlightSchedule.objects.all()
serializer = FlightScheduleSerializer(schedule, many=True)
return Response(serializer.data)
You can define the source with field_name in your serializer as follows.
I have used source='TailNumber.number'. Please use the right field_name in place of number
class UserProfileSerializer(serializers.ModelSerializer):
tail_number = serializers.CharField(source='TailNumber.number', read_only=True)
flight_number = ....(change as above)
class Meta:
model = FlightSchedule
fields = ['tail_number', 'flight_number', 'origin_port_code', 'destination_port_code', 'flight_departure_time',
'flight_number_schedule']
You could simply add them as if they were attributes.
flight_number_str = serializers.ReadOnlyField(source='flight_number.flight_number')
First flight_number is the attribute of FlightScheduleDetail, then the one of FlightSchedule
and then add it to the list of fields fields = [..., 'flight_number_str']
Otherwise you may have a look at nested relationships in DRF which can offer more possibilities also.
Another alternative is to use the depth option in a serializer. It is to specify nested serialization - doc
class AccountSerializer(serializers.ModelSerializer):
class Meta:
model = Account
fields = ('id', 'account_name', 'users', 'created')
depth = 1
If users is a foreign key or manytomany key the serializer will display the users as an object and not as a key.
The depth option should be set to an integer value that indicates
the depth of relationships that should be traversed before reverting
to a flat representation.

Django - Serialize parents associations

I am trying to create a serialized RESTful response from a One to N relationship.
I have a table Lexicon, primary key lexicon_id, I have another table lexicon_attributes, primary key lexicon_attribute_id, foreign key lexicon_id
class Lexicons(models.Model):
"""
Holds all words
"""
lexicon_id = models.BigIntegerField(primary_key=True)
word = models.TextField(blank=True, null=True)
date_created = models.DateTimeField(blank=True, null=True)
date_modified = models.DateTimeField(blank=True, null=True)
class Meta:
managed = True
db_table = 'lexicons'
class LexiconAttributes(models.Model):
class Meta:
managed = True
db_table = 'lexicon_attributes'
lexicon_attribute_id = models.AutoField(primary_key=True)
lexicon_id = models.ForeignKey('Lexicons', db_column='lexicon_id', related_name="lexicon_attributes")
is_verb = models.CharField(max_length=1, blank=True, null=True)
is_plural = models.CharField(max_length=1, blank=True, null=True)
is_past_tense = models.CharField(max_length=1, blank=True, null=True)
serializer
class LexiconAttributesSerializer(serializers.ModelSerializer):
class Meta:
model = LexiconAttributes
fields = '__all__'
class LexiconsSerializer(serializers.ModelSerializer):
lexicon_attributes = LexiconAttributesSerializer(source='*', many=False)
class Meta:
model = Lexicons
When I make a request for /lexicons/2/
{
"lexicon_id": 2,
"lexicon_attributes": {
"lexicon_id": 2
},
"word": "computer",
"date_created": "2015-07-30T20:29:19Z",
"date_modified": "2015-07-30T20:29:19Z"
}
How do I get the other fields in lexicon_attributes table
FYI I am week two into Django, my app was originally done in Cakephp3
class LexiconsSerializer(serializers.ModelSerializer):
lexicon_attributes = LexiconAttributesSerializer()
class Meta:
model = Lexicons
fields = '__all__'
fixed the problem for me after 3 days

Django Models.py Database Design Feedback

Based on my previous question and feedback I received I have redesigned my Models and need some feedback before I run the "syncdb".
My concerns are mostly ForeignKeys and the one ManyToManyField in the Restaurant table. Should also the ManyTomany field have the through='' value and what the value should be?
Any feedback is appreciated!
Models
class Restaurant(models.Model):
id = models.AutoField(primary_key=True, db_column='id')
name = models.CharField(max_length=50L, db_column='name', blank=True)
address = models.CharField(max_length=100L, blank=True)
city_id = models.ForeignKey('City', related_name="restaurant_city")
location_id = models.ForeignKey('Location', related_name="restaurant_location")
hood_id = models.ForeignKey('Hood', null=True, blank=True, related_name="restaurant_hood")
listingrole_id = models.ForeignKey('Listingrole', related_name="restaurant_listingrole")
cuisine_types = models.ManyToManyField('Cuisinetype', null=True, blank=True, related_name="restaurant_cuisinetype")
class Meta:
db_table = 'restaurant'
class City(models.Model):
id = models.AutoField(primary_key=True, db_column='id')
name = models.CharField(max_length=50L, db_column='city')
state = models.CharField(max_length=50L, db_column='state', blank=True, null=True)
class Meta:
db_table = 'city'
class Cuisinetype(models.Model):
id = models.AutoField(primary_key=True, db_column='id')
name = models.CharField(max_length=50L, db_column='cuisine', blank=True) # Field name made lowercase.
class Meta:
db_table = 'cuisinetype'
class Location(models.Model):
id = models.AutoField(primary_key=True, db_column='id')
name = models.CharField(max_length=50L, db_column='location', blank=False, null=False)
city = models.ForeignKey('City', related_name="location_city")
class Meta:
db_table = 'location'
class Hood(models.Model):
id = models.AutoField(primary_key=True, db_column='id')
name = models.CharField(max_length=50L, db_column='hood')
city = models.ForeignKey('City', related_name='hood_city')
location = models.ForeignKey('Location', related_name='hood_location')
class Meta:
db_table = 'hood'
class Listingrole(models.Model):
id = models.AutoField(primary_key=True, db_column='id')
name = models.CharField(max_length=50L, db_column='listingrole', blank=True) # Field name made lowercase.
class Meta:
db_table = 'listingrole'
....
Having into account the concept and meaning of coisine_types you don't have to make the relationship using through keyword. You use it (mostly) when there is some information about the relation it self.
According Django documentation:
The most common use for this option is when you want to associate extra data with a many-to-many relationship.
See explanation here: Extra fields on many-to-many relationships

Categories